<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="baidu-site-verification" content="L6Lm9d5Crl"/>
  
  
  
  
  <title>昌晓的Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="昌晓的Blog">
<meta property="og:type" content="website">
<meta property="og:title" content="昌晓的Blog">
<meta property="og:url" content="https://a_bowl_of_tea.gitee.io/chen-changxiao/index.html">
<meta property="og:site_name" content="昌晓的Blog">
<meta property="og:description" content="昌晓的Blog">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="昌晓">
<meta name="twitter:card" content="summary">
  
    <link rel="alternative" href="/atom.xml" title="昌晓的Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/img/e.jpg">
  
  
  
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.5.0/animate.min.css">

  
  
<link rel="stylesheet" href="/chen-changxiao/css/style.css">

  <link rel="stylesheet" href="/font-awesome/css/font-awesome.min.css">
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
  
    
    
  
  
      <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  
  <!-- 加载特效 -->
    <script src="/js/pace.js"></script>
    <link href="/css/pace/pace-theme-flash.css" rel="stylesheet" />
  <script>
      var yiliaConfig = {
          fancybox: true,
          animate: true,
          isHome: true,
          isPost: false,
          isArchive: false,
          isTag: false,
          isCategory: false,
          open_in_new: false
      }
  </script>
<meta name="generator" content="Hexo 5.4.0"></head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        
<script src="https://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>

        <a href="/" class="profilepic">
            
            <img lazy-src="/img/myavatar.jpg" class="js-avatar">
            
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/"></a></h1>
        </hgroup>
        
        
            <form>
                <input type="text" class="st-default-search-input search" id="local-search-input" placeholder="搜索一下" autocomplete="off">
            </form>
            <div id="local-search-result"></div>
        
        
            <script type="text/javascript">
                (function() {
                    'use strict';
                    function getMatchData(keyword, data) {
                        var matchData = [];
                        for(var i =0;i<data.length;i++){
                            if(data[i].title.toLowerCase().indexOf(keyword)>=0) 
                                matchData.push(data[i])
                        }
                        return matchData;
                    }
                    var $input = $('#local-search-input');
                    var $resultContent = $('#local-search-result');
                    $input.keyup(function(){
                        $.ajax({
                            url: '/search.json',
                            dataType: "json",
                            success: function( json ) {
                                var str='<ul class=\"search-result-list\">';                
                                var keyword = $input.val().trim().toLowerCase();
                                $resultContent.innerHTML = "";
                                if ($input.val().trim().length <= 0) {
                                    $resultContent.empty();
                                    $('#switch-area').show();
                                    return;
                                }
                                var results = getMatchData(keyword, json);
                                if(results.length === 0){
                                    $resultContent.empty();
                                    $('#switch-area').show();
                                    return;
                                } 
                                for(var i =0; i<results.length; i++){
                                    str += "<li><a href='"+ results[i].url +"' class='search-result-title'>"+ results[i].title +"</a></li>";
                                }
                                str += "</ul>";
                                $resultContent.empty();
                                $resultContent.append(str);
                                $('#switch-area').hide();
                            }
                        });
                    });
                })();
            </script>
        
        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        
        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a  href="/chen-changxiao/archives/">所有文章</a></li>
                        
                            <li><a  href="/chen-changxiao/categories/%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/">玩转开发工具</a></li>
                        
                            <li><a  href="/chen-changxiao/categories/digital">玩转数码</a></li>
                        
                            <li><a  href="/chen-changxiao/categories/algorithm">算法学习</a></li>
                        
                            <li><a  href="/chen-changxiao/about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fl gitee"  target="_blank" href="https://gitee.com/a_bowl_of_tea" title="gitee">gitee</a>
                            
                                <a class="fl weibo"  target="_blank" href="/chen-changxiao/xxxxxxxx" title="weibo">weibo</a>
                            
                                <a class="fl rss"  target="_blank" href="/chen-changxiao/atom.xml" title="rss">rss</a>
                            
                        </ul>
                    </nav>
                </section>
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        
                    </div>
                </section>
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a target="_blank"  class="main-nav-link switch-friends-link" href="https://blog.csdn.net/weixin_44884608?spm=1000.2115.3001.5343">csdn</a>
                    
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">爱动漫,爱游戏,爱编程,爱运动,爱的太多了!</div>
                </section>
                
            </div>
        </div>
    </header>
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页"></a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                
                    <img lazy-src="/img/myavatar.jpg" class="js-avatar">
                
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页"></a></h1>
            </hgroup>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="/chen-changxiao/archives/">所有文章</a></li>
                
                    <li><a href="/chen-changxiao/categories/%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/">玩转开发工具</a></li>
                
                    <li><a href="/chen-changxiao/categories/digital">玩转数码</a></li>
                
                    <li><a href="/chen-changxiao/categories/algorithm">算法学习</a></li>
                
                    <li><a href="/chen-changxiao/about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                <div class="social">
                    
                        <a class="gitee" target="_blank" href="https://gitee.com/a_bowl_of_tea" title="gitee">gitee</a>
                    
                        <a class="weibo" target="_blank" href="/chen-changxiao/xxxxxxxx" title="weibo">weibo</a>
                    
                        <a class="rss" target="_blank" href="/chen-changxiao/atom.xml" title="rss">rss</a>
                    
                </div>
            </nav>
        </header>
    </div>
</nav>
      <div class="body-wrap">
  
    <article id="post-drf五个接口的快速实现方法" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/drf%E4%BA%94%E4%B8%AA%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%BF%AB%E9%80%9F%E5%AE%9E%E7%8E%B0%E6%96%B9%E6%B3%95/" class="article-date">
      <time datetime="2021-11-23T11:00:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/drf%E4%BA%94%E4%B8%AA%E6%8E%A5%E5%8F%A3%E7%9A%84%E5%BF%AB%E9%80%9F%E5%AE%9E%E7%8E%B0%E6%96%B9%E6%B3%95/">drf五个接口的快速实现方法</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h2 id="视图类的两个视图基类-APIView和GenericAPIView"><a href="#视图类的两个视图基类-APIView和GenericAPIView" class="headerlink" title="视图类的两个视图基类(APIView和GenericAPIView)"></a>视图类的两个视图基类(APIView和GenericAPIView)</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 视图基类APIView和视图基类GenericAPIView的导入方式</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> GenericAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> APIView</span><br><span class="line"></span><br><span class="line">我们发现在写不同表模型类的接口的时候，都大差不差，代码明显冗余，如何解决这种问题，需要用到视图类的两个视图基类</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> GenericAPIView</span><br><span class="line">GenericAPIView类有两个重要的类属性</span><br><span class="line">queryset = <span class="literal">None</span></span><br><span class="line">serializer_class = <span class="literal">None</span></span><br><span class="line"></span><br><span class="line">可以将这两个类属性写在views类视图函数里面</span><br><span class="line">queryset = models.Book.objects.<span class="built_in">all</span>()  <span class="comment"># 需要序列化的表的所有数据</span></span><br><span class="line">serializer_class = 序列化器类  <span class="comment"># 你要使用的序列化或者反序列化的类</span></span><br><span class="line"></span><br><span class="line"><span class="number">1.</span>虽然有queryset，但是我们一般用get_queryset方法，等同于queryset</span><br><span class="line"> <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request</span>):</span></span><br><span class="line">        book_queryset = self.queryset  <span class="comment"># 对象调用类的属性</span></span><br><span class="line">        book_queryset = self.get_queryset()  <span class="comment"># 对象调用类的方法</span></span><br><span class="line">        book_queryset = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">前面两个等同于第三个，只不过前面两个继承的是GenericAPIView类</span><br><span class="line">而第三个继承的类是APIView</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>虽然有serializer_class类属性，但是我们一般用get_serializer方法，等同于serializer_class</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request</span>):</span></span><br><span class="line">        book = self.serializer_class(instance=book_queryset, many=<span class="literal">True</span>)</span><br><span class="line">        book = self.get_serializer(instance=book_queryset, many=<span class="literal">True</span>)</span><br><span class="line">        book = BookSerializers(instance=book_queryset, many=<span class="literal">True</span>)</span><br><span class="line">前面两个等同于第三个，只不过前面两个继承的是GenericAPIView类</span><br><span class="line">而第三个继承的类是APIView</span><br><span class="line"></span><br><span class="line"><span class="number">3.</span>获取单条模型表的数据</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self,request,pk</span>):</span></span><br><span class="line">        book_obj = models.Book.objects.<span class="built_in">filter</span>(pk=pk).first()</span><br><span class="line">        book_obj = self.get_objects()</span><br><span class="line"><span class="number">4.</span>Response返回的时候</span><br><span class="line">正常返回，跟APIView一样</span><br><span class="line"><span class="number">5.</span>总结</span><br><span class="line">首先，路由方面还是不变，分俩个路由</span><br><span class="line">path(<span class="string">&#x27;books/&#x27;</span>, views.MyBooks.as_view()),</span><br><span class="line">path(<span class="string">&#x27;books/&lt;int:pk&gt;/&#x27;</span>, views.MyBook.as_view())</span><br><span class="line">其次views.py文件中的两个CBV类也不变</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyBooks</span>   和   <span class="title">class</span> <span class="title">MyBook</span></span></span><br><span class="line"><span class="class">---最后这两个视图类<span class="title">MyBooks</span>和<span class="title">MyBook</span>都继承了<span class="title">GenericAPIView</span>类</span></span><br><span class="line"><span class="class">---继承<span class="title">GenericAPIView</span>类</span></span><br><span class="line"><span class="class">---两个类属性:</span></span><br><span class="line">    queryset = <span class="literal">None</span></span><br><span class="line">    serializer_class = <span class="literal">None</span></span><br><span class="line">---三个方法:</span><br><span class="line">    self.get_object()  <span class="comment"># 获取models表中的单条数据</span></span><br><span class="line">    self.get_serializer(instance=<span class="literal">None</span>,data=<span class="literal">None</span>)</span><br><span class="line">    self.get_queryset()  <span class="comment"># 获取要序列化的数据</span></span><br></pre></td></tr></table></figure>

<h2 id="五个视图扩展类"><a href="#五个视图扩展类" class="headerlink" title="五个视图扩展类()"></a>五个视图扩展类()</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">基于两个视图基类的进一步封装，让代码冗余减少</span><br><span class="line">继承GenericAPIView类加五个视图扩展类</span><br><span class="line">五个试图扩展类</span><br><span class="line"><span class="keyword">from</span> rest_framework.mixins <span class="keyword">import</span> ListModelMixin</span><br><span class="line"><span class="keyword">from</span> rest_framework.mixins <span class="keyword">import</span> RetrieveModelMixin</span><br><span class="line"><span class="keyword">from</span> rest_framework.mixins <span class="keyword">import</span> UpdateModelMixin</span><br><span class="line"><span class="keyword">from</span> rest_framework.mixins <span class="keyword">import</span> DestroyModelMixin</span><br><span class="line"><span class="keyword">from</span> rest_framework.mixins <span class="keyword">import</span> CreateModelMixin</span><br><span class="line"></span><br><span class="line">首先我们需要在views的视图类继承GenericAPIView+任意一个五个视图扩展类</span><br><span class="line"><span class="number">1.</span>如果加的是ListModelMixin视图扩展类，那么就相当于get获取所有图书信息</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyBooks</span>(<span class="params">GenericAPIView,ListModelMixin</span>):</span></span><br><span class="line">    queryset = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">    serializer_class = BookSerializers</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self,request</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.<span class="built_in">list</span>(request)</span><br><span class="line"><span class="number">2.</span>如果想新增一个数据，需要加CreateModelMixin视图扩展类</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">post</span>(<span class="params">self,request</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.create(request)</span><br><span class="line">    需要注意的是它还有一个perform_create(self,serializer)方法，该方法是保存校验通过的数据，我们可以通过对他的重写，从而达到当保存多表的时候，实现实时的更新.serializer是校验通过的数据serializer.save()</span><br><span class="line"><span class="number">3.</span>如果想获取一个图书信息，需要用到RetrieveModelMixin试图扩展类</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.retrieve(request, *args, **kwargs)</span><br><span class="line"><span class="number">4.</span>如果想修改一个图书信息，需要用到UpdateModelMixin视图扩展类</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">put</span>(<span class="params">self,request,*args,**kwargs</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.update(request,*args,**kwargs)</span><br><span class="line">    </span><br><span class="line"><span class="number">5.</span>如果想删除一个图书信息，需要用到DestroyModelMixin视图扩展类</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">delete</span>(<span class="params">self,request,*args,**kwargs</span>):</span></span><br><span class="line">        <span class="keyword">return</span> self.destroy(request,*args,**kwargs)</span><br><span class="line">需要注意的是它也写了一个方法perform_destroy(self,instance)</span><br><span class="line">我们可以重写这个方法，在删除之前做一点事情</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="number">6.</span>总结，GenericAPIView类加五个视图扩展类写五个接口的步骤</span><br><span class="line">首先，路由方面还是不变，分俩个路由</span><br><span class="line">path(<span class="string">&#x27;books/&#x27;</span>, views.MyBooks.as_view()),</span><br><span class="line">path(<span class="string">&#x27;books/&lt;int:pk&gt;/&#x27;</span>, views.MyBook.as_view())</span><br><span class="line">其次views.py文件中的两个CBV类也不变</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyBooks</span>   和   <span class="title">class</span> <span class="title">MyBook</span></span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class"># 最后是<span class="title">MyBooks</span>类继承了<span class="title">GenericAPIView</span>加两个视图扩展类</span></span><br><span class="line"><span class="class"># <span class="title">MyBook</span>类继承了<span class="title">GenericAPIView</span>加三个视图扩展类</span></span><br></pre></td></tr></table></figure>

<h2 id="九个视图子类"><a href="#九个视图子类" class="headerlink" title="九个视图子类()"></a>九个视图子类()</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 九个视图子类的模块导入如下</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> ListAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> CreateAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> RetrieveAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> UpdateAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> DestroyAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> ListCreateAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> RetrieveUpdateAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> RetrieveDestroyAPIView</span><br><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> RetrieveUpdateDestroyAPIView</span><br><span class="line"></span><br><span class="line"><span class="number">1.</span>视图子类ListAPIView  <span class="comment"># 等同于写了一个获取所有图书的get请求方式的接口</span></span><br><span class="line">视图子类ListAPIView = 视图基类GenericAPIView + 视图扩展类ListModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ListAPIView</span>(<span class="params">mixins.ListModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                  GenericAPIView</span>):</span></span><br><span class="line">ListAPIView视图子类继承了ListModelMixin视图扩展类和GenericAPIView视图基类</span><br><span class="line"><span class="number">2.</span>视图子类CreateAPIView  <span class="comment"># 等同于写了一个新增一个图书的post请求方式的接口</span></span><br><span class="line">视图子类CreateAPIView = 视图基类GenericAPIView + 视图扩展类CreateModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">CreateAPIView</span>(<span class="params">mixins.CreateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                    GenericAPIView</span>):</span></span><br><span class="line"></span><br><span class="line"><span class="number">3.</span>视图子类RetrieveAPIView  <span class="comment"># 等同于写了一个查询一本图书的get请求方式的接口</span></span><br><span class="line">视图子类RetrieveAPIView = 视图基类GenericAPIView + 视图扩展类RetrieveModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RetrieveAPIView</span>(<span class="params">mixins.RetrieveModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                      GenericAPIView</span>):</span></span><br><span class="line"><span class="number">4.</span>视图子类UpdateAPIView  <span class="comment"># 等同于写了一个修改一本图书的put请求方式的接口</span></span><br><span class="line">视图子类UpdateAPIView = 视图基类GenericAPIView + 视图扩展类UpdateModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UpdateAPIView</span>(<span class="params">mixins.UpdateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                    GenericAPIView</span>):</span></span><br><span class="line"><span class="number">5.</span>视图子类DestroyAPIView  <span class="comment"># 等同于写了一个删除一本图书的delete请求方式的接口</span></span><br><span class="line">视图子类DestroyAPIView = 视图基类GenericAPIView + 视图扩展类DestroyModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">DestroyAPIView</span>(<span class="params">mixins.DestroyModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                     GenericAPIView</span>):</span></span><br><span class="line">    </span><br><span class="line"><span class="number">6.</span>视图子类ListCreateAPIView  <span class="comment"># 等同于写了一个获取所有图书和新增一本图书的get和post请求方式的两个接口</span></span><br><span class="line">视图子类ListCreateAPIView = 视图基类GenericAPIView + 视图扩展类ListModelMixin + 视图扩展类CreateModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ListCreateAPIView</span>(<span class="params">mixins.ListModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                        mixins.CreateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                        GenericAPIView</span>):</span></span><br><span class="line"><span class="number">7.</span>视图子类RetrieveUpdateAPIView  <span class="comment"># 等同于写了一个获取一本图书和修改一本图书的get和put请求方式的两个接口</span></span><br><span class="line">视图子类RetrieveUpdateAPIView = 视图基类GenericAPIView + 视图扩展类RetrieveModelMixin + 视图扩展类UpdateModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RetrieveUpdateAPIView</span>(<span class="params">mixins.RetrieveModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                            mixins.UpdateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                            GenericAPIView</span>):</span></span><br><span class="line"><span class="number">8.</span>视图子类RetrieveDestroyAPIView  <span class="comment"># 等同于写了一个获取一本图书和删除一本图书的get和delete请求方式的两个接口</span></span><br><span class="line">视图子类RetrieveDestroyAPIView = 视图基类GenericAPIView + 视图扩展类</span><br><span class="line">RetrieveModelMixin + 视图扩展类DestroyModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RetrieveDestroyAPIView</span>(<span class="params">mixins.RetrieveModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                             mixins.DestroyModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                             GenericAPIView</span>):</span></span><br><span class="line"><span class="number">9.</span>视图子类RetrieveUpdateDestroyAPIView  <span class="comment"># 等同于写了一个获取一本图书和修改一本图书以及删除一本图书的get和put和delete请求方式的三个接口</span></span><br><span class="line">视图子类RetrieveUpdateDestroyAPIView = 视图基类GenericAPIView + 视图扩展类RetrieveModelMixin + 视图扩展类UpdateModelMixin + 视图扩展类DestroyModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RetrieveUpdateDestroyAPIView</span>(<span class="params">mixins.RetrieveModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                                   mixins.UpdateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                                   mixins.DestroyModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                                   GenericAPIView</span>):</span></span><br><span class="line"><span class="number">10.</span>总结</span><br><span class="line">首先，路由方面还是不变，分俩个路由</span><br><span class="line">path(<span class="string">&#x27;books/&#x27;</span>, views.MyBooks.as_view()),</span><br><span class="line">path(<span class="string">&#x27;books/&lt;int:pk&gt;/&#x27;</span>, views.MyBook.as_view())</span><br><span class="line">其次views.py文件中的两个CBV类也不变</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyBooks</span>   和   <span class="title">class</span> <span class="title">MyBook</span></span></span><br><span class="line"><span class="class">--只需要继承你想要实现的接口类</span></span><br><span class="line"><span class="class">--随机组合，只要满足五个接口就可以</span></span><br></pre></td></tr></table></figure>

<h2 id="视图集"><a href="#视图集" class="headerlink" title="视图集"></a>视图集</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 四个视图集,需要导入视图集模块</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ModelViewSet</span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ReadOnlyModelViewSet</span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ViewSet</span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> GenericViewSet </span><br><span class="line"><span class="number">1.</span>视图集ModelViewSet  <span class="comment"># 等同于写了获取所有，获取单个，新增一个，修改一个，删除一个的get,get,post,put,delete五个请求方式的接口</span></span><br><span class="line">视图集ModelViewSet = 视图基类的子类GenericViewSet + ListModelMixin视图扩展类</span><br><span class="line">+ 视图扩展类CreateModelMixin + 视图扩展类RetrieveModelMixin </span><br><span class="line">+ 视图扩展类UpdateModelMixin + 视图扩展类DestroyModelMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ModelViewSet</span>(<span class="params">mixins.CreateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                   mixins.RetrieveModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                   mixins.UpdateModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                   mixins.DestroyModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                   mixins.ListModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                   GenericViewSet</span>):</span></span><br><span class="line"><span class="number">2.</span>视图集ReadOnlyModelViewSet</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ReadOnlyModelViewSet</span>(<span class="params">mixins.RetrieveModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                           mixins.ListModelMixin,</span></span></span><br><span class="line"><span class="params"><span class="class">                           GenericViewSet</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="number">3.</span>视图集ViewSet  <span class="comment"># 等同于APIView + ViewSetMixin</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">ViewSet</span>(<span class="params">ViewSetMixin, views.APIView</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="number">4.</span>GenericViewSet  <span class="comment"># 等同于GenericAPIView + ViewSetMixin</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GenericViewSet</span>(<span class="params">ViewSetMixin, generics.GenericAPIView</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="number">5.</span>视图集的父类GenericViewSet</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GenericViewSet</span>(<span class="params">ViewSetMixin, generics.GenericAPIView</span>):</span></span><br><span class="line"><span class="number">6.</span>视图集ModelViewSet的父类GenericViewSet的父类ViewSetMixin</span><br><span class="line">所以说我们在as_view方法里面填字典能够映射，是该类实现的</span><br><span class="line">路由匹配成功执行--&gt;as_view方法，该方法是ViewSetMixin的as_view---&gt;执行之后，他会将字典<span class="keyword">for</span>循环解压赋值成key,value的形式，其中通过<span class="built_in">getattr</span>反射自己创建的类获取value函数的内存地址，然后再通过<span class="built_in">setattr</span>将key的内存地址替换成了value函数的内存地址---&gt;执行value()--&gt;后面的就跟View执行的流程大差不大了</span><br><span class="line"><span class="comment"># 所以说只要继承了ViewSetMixin类，路由写法就发生了变化，视图类中方法可以随意命名，只需要再路由中映射即可，也就是value值改变就可以</span></span><br><span class="line"></span><br><span class="line"><span class="number">7.</span>总结</span><br><span class="line">首先，路由方面跟前面的大差不差，分俩个路由，唯一的区别是as_view里面有参数，该参数是字典的形式，字典中的key代表请求方式，字典中的value代表的是该请求方式发出时候需要执行的函数。如&#123;<span class="string">&#x27;get&#x27;</span>:<span class="string">&#x27;name&#x27;</span>,<span class="string">&#x27;post&#x27;</span>:<span class="string">&#x27;egon&#x27;</span>&#125;</span><br><span class="line">比如get请求方式发出的时候，会执行name函数，post请求发出的时候会执行egon函数。当然前提肯定是路由匹配成功，</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># views.py文件中的代码</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ModelViewSet</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyBooks</span>(<span class="params">ModelViewSet</span>):</span></span><br><span class="line">    queryset = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">    serializer_class = 序列化器类内存地址</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 路由urls.py中的代码</span></span><br><span class="line">path(<span class="string">&#x27;books/&#x27;</span>, views.MyBooks.as_view(&#123;<span class="string">&#x27;get&#x27;</span>:<span class="string">&#x27;list&#x27;</span>,<span class="string">&#x27;post&#x27;</span>:<span class="string">&#x27;create&#x27;</span>&#125;)),</span><br><span class="line">path(<span class="string">&#x27;books/&lt;int:pk&gt;/&#x27;</span>, views.MyBook.as_view(&#123;<span class="string">&#x27;get&#x27;</span>:<span class="string">&#x27;retrieve&#x27;</span>,<span class="string">&#x27;put&#x27;</span>:<span class="string">&#x27;update&#x27;</span>,<span class="string">&#x27;delete&#x27;</span>:<span class="string">&#x27;destroy&#x27;</span>&#125;))</span><br></pre></td></tr></table></figure>



<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">需要知道每个关键的方法都在那个父类</span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">list</span>():</span>  <span class="comment"># 在ListModelMixin中写了list方法</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">create</span>():</span>  <span class="comment"># 在CreateModelMixin中写了create方法</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">retrieve</span>():</span>  <span class="comment"># 在RetrieveModelMixin中写了retrieve方法</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">update</span>():</span>  <span class="comment"># 在UpdateModelMixin中写了update方法</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">destroy</span>():</span>  <span class="comment"># 在DestroyModelMixin中写了destroy方法</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">perform_create</span>(<span class="params">self,serializer</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">    <span class="comment"># 在CreateModelMixin中写了perform_create方法</span></span><br><span class="line">    <span class="comment"># 这个是post请求方式来的时候执行post函数中的create函数中的perform_create函数，该函数是专门创建新数据的函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">perform_destroy</span>(<span class="params">self,instance</span>):</span></span><br><span class="line">    <span class="keyword">pass</span></span><br><span class="line">    <span class="comment"># 在DestroyModelMixin中写了perform_destroy方法</span></span><br><span class="line">    <span class="comment"># 这个是delete请求方式来的时候执行delete函数中的perform_destroy函数，该函数是专门处理删除数据的函数</span></span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">视图集ModelViewSet--&gt;GenericViewSet--&gt;视图基类GenericAPIView--&gt;视图基类APIView--&gt;View--&gt;<span class="built_in">object</span></span><br><span class="line"></span><br><span class="line">视图集ModelViewSet--&gt;GenericViewSet--&gt;ViewSetMixin--&gt;<span class="built_in">object</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">视图集ModelViewSet有<span class="number">6</span>个父类</span><br></pre></td></tr></table></figure>


      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-全局规定请求格式编码与响应格式编码" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/%E5%85%A8%E5%B1%80%E8%A7%84%E5%AE%9A%E8%AF%B7%E6%B1%82%E6%A0%BC%E5%BC%8F%E7%BC%96%E7%A0%81%E4%B8%8E%E5%93%8D%E5%BA%94%E6%A0%BC%E5%BC%8F%E7%BC%96%E7%A0%81/" class="article-date">
      <time datetime="2021-11-23T11:00:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/%E5%85%A8%E5%B1%80%E8%A7%84%E5%AE%9A%E8%AF%B7%E6%B1%82%E6%A0%BC%E5%BC%8F%E7%BC%96%E7%A0%81%E4%B8%8E%E5%93%8D%E5%BA%94%E6%A0%BC%E5%BC%8F%E7%BC%96%E7%A0%81/">全局规定请求格式编码与响应格式编码</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h2 id="全局规定请求格式编码"><a href="#全局规定请求格式编码" class="headerlink" title="全局规定请求格式编码"></a>全局规定请求格式编码</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 全局规定请求格式编码，settings文件配置</span></span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">&#x27;DEFAULT_PARSER_CLASSES&#x27;</span>: [</span><br><span class="line">        <span class="string">&#x27;rest_framework.parsers.JSONParser&#x27;</span>,  <span class="comment"># 第一种编码</span></span><br><span class="line">        <span class="string">&#x27;rest_framework.parsers.FormParser&#x27;</span>,  <span class="comment"># 第二种编码</span></span><br><span class="line">        <span class="string">&#x27;rest_framework.parsers.MultiPartParser&#x27;</span>  <span class="comment"># 第三种编码</span></span><br><span class="line">    ],</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果注销第一种编码，也就相当于前端在新增或者修改的时候，提交的数据不能是json格式的编码</span></span><br><span class="line"><span class="comment"># 如果注销第二种编码，也就相当于前端在新增或者修改的时候，提交的数据不能是form-data格式的编码</span></span><br><span class="line"><span class="comment"># 如果注销第三种编码，也就相当于前端在新增或者修改的时候，提交的数据不能是url-encoded格式的编码</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 同样，如果只写一种或者两种，也就是说只接收前端传过来的某一种或者某两种编码格式</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 局部规定请求格式编码，views文件中的视图类中写</span></span><br><span class="line">parser_classes = [FormParser]  <span class="comment"># 括号内代表的是url-encoded编码格式</span></span><br><span class="line">parser_classes = [JSONParser]  <span class="comment"># 括号内代表的是json编码格式数据</span></span><br><span class="line">parser_classes = [MultiPartParser]  <span class="comment"># 代表的是form-data编码格式数据</span></span><br></pre></td></tr></table></figure>

<h2 id="规定响应格式编码"><a href="#规定响应格式编码" class="headerlink" title="规定响应格式编码"></a>规定响应格式编码</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 全局规定响应格式编码，settings文件配置</span></span><br><span class="line"></span><br><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    <span class="string">&#x27;DEFAULT_RENDERER_CLASSES&#x27;</span>: [</span><br><span class="line">        <span class="string">&#x27;rest_framework.renderers.JSONRenderer&#x27;</span>,  <span class="comment"># 第一种编码格式</span></span><br><span class="line">        <span class="string">&#x27;rest_framework.renderers.BrowsableAPIRenderer&#x27;</span>,  <span class="comment"># 第二种</span></span><br><span class="line">    ],&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果注销第一种编码，也就相当于后端提交数据(Response返回的时候)不能是json格式的数据返回，而是变成了其他格式的数据</span></span><br><span class="line"><span class="comment"># 如果注销第二种编码，也就相当于后端提交数据(Response返回的时候)不能是浏览器格式的数据返回，而是变成了Json或者其他格式的数据</span></span><br><span class="line"><span class="comment"># 同理如果只写一种，也就是指定那一种编码格式返回到前端</span></span><br><span class="line">renderer_classes = [JSONParser]</span><br><span class="line">renderer_classes = [BrowsableAPIRenderer]</span><br></pre></td></tr></table></figure>

<h2 id="编码格式规定的优先级"><a href="#编码格式规定的优先级" class="headerlink" title="编码格式规定的优先级"></a>编码格式规定的优先级</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">局部 &gt; 全局(django配置文件) &gt; drf配置文件</span><br></pre></td></tr></table></figure>

<h2 id="Response的参数"><a href="#Response的参数" class="headerlink" title="Response的参数"></a>Response的参数</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">data  <span class="comment"># 字典或者列表或者字符串，可以将列表或者字典以json格式返回，字符串的话返回到前端还是字符串，返回到前端的数据放在了响应体中</span></span><br><span class="line">status  <span class="comment"># 状态码，可以直接写数字，也可以调drf中的配置常量，相当于填写的数</span></span><br><span class="line">template_name  <span class="comment"># 可以填一个html文件名字，会将该文件返回到前端</span></span><br><span class="line">headers  <span class="comment"># 响应头,可以放一个字典，会以键值对的形式放回给前端响应头里面</span></span><br><span class="line">content_type  <span class="comment"># 响应的编码格式</span></span><br><span class="line">exception  <span class="comment"># 响应的异常信息</span></span><br></pre></td></tr></table></figure>


      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-后端创建虚拟环境" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/%E5%90%8E%E7%AB%AF%E5%88%9B%E5%BB%BA%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83/" class="article-date">
      <time datetime="2021-11-23T10:09:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/%E5%90%8E%E7%AB%AF%E5%88%9B%E5%BB%BA%E8%99%9A%E6%8B%9F%E7%8E%AF%E5%A2%83/">后端创建虚拟环境</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h1 id="创建虚拟环境"><a href="#创建虚拟环境" class="headerlink" title="创建虚拟环境"></a>创建虚拟环境</h1><h3 id="1-作用"><a href="#1-作用" class="headerlink" title="1 作用"></a>1 作用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span>、使不同应用开发环境相互独立</span><br><span class="line"><span class="number">2</span>、环境升级不影响其他应用，也不会影响全局的python环境</span><br><span class="line"><span class="number">3</span>、防止出现包管理混乱及包版本冲突</span><br></pre></td></tr></table></figure>

<h2 id="2-直接使用Pycharm创建虚拟环境"><a href="#2-直接使用Pycharm创建虚拟环境" class="headerlink" title="2 直接使用Pycharm创建虚拟环境"></a>2 直接使用Pycharm创建虚拟环境</h2><p>##3  使用命令创建虚拟环境</p>
<h3 id="3-1-安装两个命令"><a href="#3-1-安装两个命令" class="headerlink" title="3.1 安装两个命令"></a>3.1 安装两个命令</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">pip3 install virtualenv</span><br><span class="line">pip3 install virtualenvwrapper-win <span class="comment"># win系统才装</span></span><br><span class="line">pip3 install virtualenvwrapper    <span class="comment"># mac和linux</span></span><br></pre></td></tr></table></figure>

<h3 id="3-2-配置虚拟环境管理器工作目录"><a href="#3-2-配置虚拟环境管理器工作目录" class="headerlink" title="3.2 配置虚拟环境管理器工作目录"></a>3.2 配置虚拟环境管理器工作目录</h3><p><code>去环境变量中加：WORKON_HOME: D:\Virtualenvs</code></p>
<h3 id="3-3-去D盘新建一个文件夹Virtualenvs"><a href="#3-3-去D盘新建一个文件夹Virtualenvs" class="headerlink" title="3.3 去D盘新建一个文件夹Virtualenvs"></a>3.3 去D盘新建一个文件夹Virtualenvs</h3><h3 id="3-4命令操作（cmd中）"><a href="#3-4命令操作（cmd中）" class="headerlink" title="3.4命令操作（cmd中）"></a>3.4命令操作（cmd中）</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 选取默认Python环境创建虚拟环境：</span></span><br><span class="line">           mkvirtualenv 虚拟环境名称</span><br><span class="line">       # 1、基于某Python环境创建虚拟</span><br><span class="line">           mkvirtualenv -p python2.7 虚拟环境名称</span><br><span class="line">           mkvirtualenv -p python3.6 虚拟环境名称</span><br><span class="line">	   # 创建并进入：以后安装模块就安装在虚拟环境里了</span><br><span class="line">	   </span><br><span class="line">       # 2、查看已有的虚拟环境</span><br><span class="line">           -- workon</span><br><span class="line"></span><br><span class="line">       # 3、使用某个虚拟环境</span><br><span class="line">           -- workon 虚拟环境名称</span><br><span class="line"></span><br><span class="line">       # 4、进入|退出 该虚拟环境的Python环境</span><br><span class="line">           -- python | exit()</span><br><span class="line"></span><br><span class="line">       # 5、为虚拟环境安装模块</span><br><span class="line">           -- pip或pip3 install 模块名</span><br><span class="line"></span><br><span class="line">       # 6、退出当前虚拟环境</span><br><span class="line">           -- deactivate</span><br><span class="line"></span><br><span class="line">       # 7、删除虚拟环境(删除当前虚拟环境要先退出)</span><br><span class="line">       	# 去相应的文件夹下删除文件夹即可</span><br><span class="line">           -- rmvirtualenv 虚拟环境名称</span><br></pre></td></tr></table></figure>

<h3 id="3-5-在pycharm中使用"><a href="#3-5-在pycharm中使用" class="headerlink" title="3.5 在pycharm中使用"></a>3.5 在pycharm中使用</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在虚拟环境下安装Django</span></span><br><span class="line">pip install django==<span class="number">2.2</span><span class="number">.2</span></span><br></pre></td></tr></table></figure>


      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-pip换源" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/pip%E6%8D%A2%E6%BA%90/" class="article-date">
      <time datetime="2021-11-23T10:05:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/pip%E6%8D%A2%E6%BA%90/">pip换源</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h1 id="pip换源"><a href="#pip换源" class="headerlink" title="pip换源"></a>pip换源</h1><h2 id="1-卸载pip3命令"><a href="#1-卸载pip3命令" class="headerlink" title="1 卸载pip3命令"></a>1 卸载pip3命令</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3 uninstall requests</span><br></pre></td></tr></table></figure>

<h2 id="2-安装pip3命令"><a href="#2-安装pip3命令" class="headerlink" title="2 安装pip3命令"></a>2 安装pip3命令</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3 install requests</span><br></pre></td></tr></table></figure>

<h2 id="3-统一修改，以后都走豆瓣源"><a href="#3-统一修改，以后都走豆瓣源" class="headerlink" title="3 统一修改，以后都走豆瓣源"></a>3 统一修改，以后都走豆瓣源</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> pip install django    国外地址，速度慢</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> pip install django -i http://pypi.douban.com/simple/</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 统一修改，以后都走豆瓣源</span></span><br><span class="line">	-1 去&#x27;C:\Users\Admin\AppData\Roaming&#x27;路径,在地址栏输入%APPDATA%，敲回车</span><br><span class="line">    </span><br><span class="line">    -2 新建 pip 文件夹并在文件夹</span><br><span class="line">    -3 新增 pip.ini 配置文件内容</span><br><span class="line">    -4 写入</span><br><span class="line">        [global]</span><br><span class="line">        index-url = http://pypi.douban.com/simple</span><br><span class="line">        [install]</span><br><span class="line">        use-mirrors =true</span><br><span class="line">        mirrors =http://pypi.douban.com/simple/</span><br><span class="line">        trusted-host =pypi.douban.com</span><br><span class="line"><span class="meta"></span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 补充</span></span><br><span class="line">	-可能自己写了模块（包），想传到pypi上，给别人用</span><br><span class="line">    -https://pypi.org/simple/</span><br></pre></td></tr></table></figure>


      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-Docker一键部署" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/Docker%E4%B8%80%E9%94%AE%E9%83%A8%E7%BD%B2/" class="article-date">
      <time datetime="2021-11-23T09:03:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/Docker%E4%B8%80%E9%94%AE%E9%83%A8%E7%BD%B2/">Docker一键部署</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h1 id="Docker一键部署"><a href="#Docker一键部署" class="headerlink" title="Docker一键部署"></a>Docker一键部署</h1><h2 id="1-安装Docker"><a href="#1-安装Docker" class="headerlink" title="1 安装Docker"></a>1 安装Docker</h2><h3 id="1-1-安装依赖"><a href="#1-1-安装依赖" class="headerlink" title="1.1 安装依赖"></a>1.1 安装依赖</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yum install -y yum-utils device-mapper-persistent-data lvm2</span><br></pre></td></tr></table></figure>

<h3 id="1-2-设置yum源"><a href="#1-2-设置yum源" class="headerlink" title="1.2 设置yum源"></a>1.2 设置yum源</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">yum-config-manager --add-repo </span><br><span class="line">https://download.docker.com/linux/centos/docker-ce.repo</span><br></pre></td></tr></table></figure>

<h3 id="1-3-安装Docker"><a href="#1-3-安装Docker" class="headerlink" title="1.3 安装Docker"></a>1.3 安装Docker</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">yum install -y docker-ce</span><br></pre></td></tr></table></figure>

<h3 id="1-4-设置开机启动"><a href="#1-4-设置开机启动" class="headerlink" title="1.4 设置开机启动"></a>1.4 设置开机启动</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">systemctl enable docker</span><br></pre></td></tr></table></figure>

<h3 id="1-5-启动-Docker"><a href="#1-5-启动-Docker" class="headerlink" title="1.5 启动 Docker"></a>1.5 启动 Docker</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">systemctl start docker</span><br></pre></td></tr></table></figure>

<h3 id="1-6-查看版本"><a href="#1-6-查看版本" class="headerlink" title="1.6 查看版本"></a>1.6 查看版本</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker version</span><br></pre></td></tr></table></figure>

<h2 id="2-安装Docker-compose"><a href="#2-安装Docker-compose" class="headerlink" title="2 安装Docker-compose"></a>2 安装Docker-compose</h2><h3 id="2-1-下载"><a href="#2-1-下载" class="headerlink" title="2.1 下载"></a>2.1 下载</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">curl -L https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m) &gt; /usr/bin/docker-compose</span><br><span class="line">sudo curl -L &quot;https://get.daocloud.io/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose</span><br></pre></td></tr></table></figure>

<h3 id="2-2-赋予执行权限"><a href="#2-2-赋予执行权限" class="headerlink" title="2.2 赋予执行权限"></a>2.2 赋予执行权限</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">chmod +x /usr/local/bin/docker-compose</span><br></pre></td></tr></table></figure>

<h3 id="2-2-查看版本"><a href="#2-2-查看版本" class="headerlink" title="2.2 查看版本"></a>2.2 查看版本</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">docker-compose --version</span><br></pre></td></tr></table></figure>

<h3 id="2-3-下载代码"><a href="#2-3-下载代码" class="headerlink" title="2.3 下载代码"></a>2.3 下载代码</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">git clone https://gitee.com/liuqingzheng/luffy.git</span><br><span class="line"><span class="meta">#</span><span class="bash"> docker-compose up -d</span></span><br></pre></td></tr></table></figure>




      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-上线" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/%E4%B8%8A%E7%BA%BF/" class="article-date">
      <time datetime="2021-11-23T05:45:08.672Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/%E4%B8%8A%E7%BA%BF/">项目上线部署</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h1 id="上线部署"><a href="#上线部署" class="headerlink" title="上线部署"></a>上线部署</h1><h2 id="1-、购买云服务器"><a href="#1-、购买云服务器" class="headerlink" title="1 、购买云服务器"></a>1 、购买云服务器</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">阿里云，腾讯云，华为云</span><br></pre></td></tr></table></figure>

<h3 id="1-1-虚拟机安装Linux教程"><a href="#1-1-虚拟机安装Linux教程" class="headerlink" title="1.1 虚拟机安装Linux教程"></a>1.1 虚拟机安装Linux教程</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://www.liuqingzheng.top/linux/%E5%<span class="number">85</span>%A5%E9%<span class="number">97</span>%A8%E5%<span class="number">88</span>%B0%E7%B2%BE%E9%<span class="number">80</span>%9A/02-Linux%E7%B3%BB%E7%BB%9F%E5%AE%<span class="number">89</span>%E8%A3%<span class="number">85</span>/</span><br></pre></td></tr></table></figure>

<h3 id="1-2-远程连接工具"><a href="#1-2-远程连接工具" class="headerlink" title="1.2 远程连接工具"></a>1.2 远程连接工具</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span>xshell  收费</span><br><span class="line"><span class="number">2.</span>finalshell 免费</span><br></pre></td></tr></table></figure>

<p>xshell远程连接服务器</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ssh root@<span class="number">8.130</span><span class="number">.176</span><span class="number">.65</span></span><br><span class="line">输入root用户密码</span><br></pre></td></tr></table></figure>

<h3 id="1-3阿里云服务配置"><a href="#1-3阿里云服务配置" class="headerlink" title="1.3阿里云服务配置"></a>1.3阿里云服务配置</h3><h4 id="更新yum源"><a href="#更新yum源" class="headerlink" title="更新yum源"></a>更新yum源</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># yum install 软件名</span></span><br><span class="line">yum update -y  <span class="comment"># 更新一下yum源</span></span><br></pre></td></tr></table></figure>

<h4 id="安装一下开发工具软件（git）-执行一个就可以"><a href="#安装一下开发工具软件（git）-执行一个就可以" class="headerlink" title="安装一下开发工具软件（git） 执行一个就可以"></a>安装一下开发工具软件（git） 执行一个就可以</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># yum install git</span></span><br><span class="line">yum -y groupinstall <span class="string">&quot;Development tools&quot;</span></span><br></pre></td></tr></table></figure>

<h4 id="安装额外依赖"><a href="#安装额外依赖" class="headerlink" title="安装额外依赖"></a>安装额外依赖</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># python 3.7的依赖</span></span><br><span class="line">yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-devel sqlite-devel psmisc libffi-devel zlib* libffi-devel  -y</span><br></pre></td></tr></table></figure>

<h2 id="2-安装Mysql（rpm包安装）"><a href="#2-安装Mysql（rpm包安装）" class="headerlink" title="2 安装Mysql（rpm包安装）"></a>2 安装Mysql（rpm包安装）</h2><h3 id="2-1-前往用户根目录"><a href="#2-1-前往用户根目录" class="headerlink" title="2.1 前往用户根目录"></a>2.1 前往用户根目录</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">切换到家路径</span></span><br><span class="line">cd ~</span><br></pre></td></tr></table></figure>

<h3 id="2-2-下载MySQL57"><a href="#2-2-下载MySQL57" class="headerlink" title="2.2 下载MySQL57"></a>2.2 下载MySQL57</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 下载mysql 5.7的rpm包</span></span><br><span class="line">wget http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm</span><br></pre></td></tr></table></figure>

<h3 id="2-3-安装mysql57"><a href="#2-3-安装mysql57" class="headerlink" title="2.3 安装mysql57"></a>2.3 安装mysql57</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: yum -y install mysql57-community-release-el7-10.noarch.rpm</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: yum -y install mysql-community-server</span></span><br></pre></td></tr></table></figure>

<h3 id="2-4-启动mysql57并查看启动状态"><a href="#2-4-启动mysql57并查看启动状态" class="headerlink" title="2.4 启动mysql57并查看启动状态"></a>2.4 启动mysql57并查看启动状态</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: systemctl start mysqld.service  <span class="comment"># 启动mysql服务</span></span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: systemctl status mysqld.service</span></span><br></pre></td></tr></table></figure>

<h3 id="2-5-查看默认密码并登录"><a href="#2-5-查看默认密码并登录" class="headerlink" title="2.5 查看默认密码并登录"></a>2.5 查看默认密码并登录</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: grep <span class="string">&quot;password&quot;</span> /var/<span class="built_in">log</span>/mysqld.log <span class="comment"># 查看随机生成的密码是什么</span></span></span><br><span class="line"><span class="meta"> #</span><span class="bash"> MMa&lt;I45gphwj</span></span><br><span class="line"><span class="meta"> #</span><span class="bash"> &gt;zd&amp;kbuGl7fs</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: mysql -uroot -p</span></span><br></pre></td></tr></table></figure>

<h3 id="2-6-修改密码"><a href="#2-6-修改密码" class="headerlink" title="2.6 修改密码"></a>2.6 修改密码</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: ALTER USER <span class="string">&#x27;root&#x27;</span>@<span class="string">&#x27;localhost&#x27;</span> IDENTIFIED BY <span class="string">&#x27;Xiao1234?&#x27;</span>;</span></span><br></pre></td></tr></table></figure>

<h2 id="3-安装Redis-源码编译安装"><a href="#3-安装Redis-源码编译安装" class="headerlink" title="3 安装Redis(源码编译安装)"></a>3 安装Redis(源码编译安装)</h2><h3 id="3-1-前往用户根目录"><a href="#3-1-前往用户根目录" class="headerlink" title="3.1 前往用户根目录"></a>3.1 前往用户根目录</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">cd ~</span><br></pre></td></tr></table></figure>

<h3 id="3-2-下载redis-5-0-5"><a href="#3-2-下载redis-5-0-5" class="headerlink" title="3.2 下载redis-5.0.5"></a>3.2 下载redis-5.0.5</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: wget http://download.redis.io/releases/redis-5.0.5.tar.gz</span></span><br><span class="line">	    http://download.redis.io/releases/redis-6.0.6.tar.gz</span><br></pre></td></tr></table></figure>

<h3 id="3-3-解压安装包"><a href="#3-3-解压安装包" class="headerlink" title="3.3 解压安装包"></a>3.3 解压安装包</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: tar -xf redis-5.0.5.tar.gz</span></span><br></pre></td></tr></table></figure>

<h3 id="3-4-进入目标文件"><a href="#3-4-进入目标文件" class="headerlink" title="3.4 进入目标文件"></a>3.4 进入目标文件</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">cd</span> redis-5.0.5</span></span><br></pre></td></tr></table></figure>

<h3 id="3-5-编译环境"><a href="#3-5-编译环境" class="headerlink" title="3.5 编译环境"></a>3.5 编译环境</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: make  <span class="comment"># 把源码编译成可执行文件</span></span></span><br></pre></td></tr></table></figure>

<h3 id="3-6-复制环境到指定路径完成安装"><a href="#3-6-复制环境到指定路径完成安装" class="headerlink" title="3.6 复制环境到指定路径完成安装"></a>3.6 复制环境到指定路径完成安装</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: cp -r ~/redis-5.0.5 /usr/<span class="built_in">local</span>/redis</span></span><br></pre></td></tr></table></figure>

<h3 id="3-7-配置redis可以后台启动：修改下方内容（可以不改）"><a href="#3-7-配置redis可以后台启动：修改下方内容（可以不改）" class="headerlink" title="3.7 配置redis可以后台启动：修改下方内容（可以不改）"></a>3.7 配置redis可以后台启动：修改下方内容（可以不改）</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: vim /usr/<span class="built_in">local</span>/redis/redis.conf</span></span><br><span class="line">daemonize yes</span><br></pre></td></tr></table></figure>

<h3 id="3-8-完成配置修改"><a href="#3-8-完成配置修改" class="headerlink" title="3.8 完成配置修改"></a>3.8 完成配置修改</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: esc</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: :wq</span></span><br></pre></td></tr></table></figure>

<h3 id="3-9-建立软连接-usr-bin-在环境变量下，以后任意路径敲这俩命令都可以"><a href="#3-9-建立软连接-usr-bin-在环境变量下，以后任意路径敲这俩命令都可以" class="headerlink" title="3.9 建立软连接 #/usr/bin/在环境变量下，以后任意路径敲这俩命令都可以"></a>3.9 建立软连接 #/usr/bin/在环境变量下，以后任意路径敲这俩命令都可以</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: ln -s /usr/<span class="built_in">local</span>/redis/src/redis-server /usr/bin/redis-server</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: ln -s /usr/<span class="built_in">local</span>/redis/src/redis-cli /usr/bin/redis-cli</span></span><br></pre></td></tr></table></figure>

<h3 id="3-10-后台运行redis"><a href="#3-10-后台运行redis" class="headerlink" title="3.10 后台运行redis"></a>3.10 后台运行redis</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">cd</span> /usr/<span class="built_in">local</span>/redis</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: redis-server ./redis.conf &amp;  <span class="comment"># 使用配置文件启动</span></span></span><br><span class="line"></span><br><span class="line">停止： ctrl + c</span><br></pre></td></tr></table></figure>

<h3 id="3-11-测试redis环境"><a href="#3-11-测试redis环境" class="headerlink" title="3.11 测试redis环境"></a>3.11 测试redis环境</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: redis-cli</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 停止 ctrl + c</span></span><br></pre></td></tr></table></figure>

<h3 id="3-12-关闭redis服务"><a href="#3-12-关闭redis服务" class="headerlink" title="3.12 关闭redis服务"></a>3.12 关闭redis服务</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pkill -f redis -9</span><br></pre></td></tr></table></figure>

<h2 id="4-安装python解释器（3-8源码安装）"><a href="#4-安装python解释器（3-8源码安装）" class="headerlink" title="4 安装python解释器（3.8源码安装）"></a>4 安装python解释器（3.8源码安装）</h2><h3 id="4-1-前往用户根目录"><a href="#4-1-前往用户根目录" class="headerlink" title="4.1 前往用户根目录"></a>4.1 前往用户根目录</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">cd</span> ~</span></span><br></pre></td></tr></table></figure>

<h3 id="4-2-解释器下载"><a href="#4-2-解释器下载" class="headerlink" title="4.2 解释器下载"></a>4.2 解释器下载</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: wget https://www.python.org/ftp/python/3.8.8/Python-3.8.8.tar.xz</span></span><br></pre></td></tr></table></figure>

<h3 id="4-3-解压安装包"><a href="#4-3-解压安装包" class="headerlink" title="4.3 解压安装包"></a>4.3 解压安装包</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: tar -xf Python-3.8.8.tar.xz</span></span><br></pre></td></tr></table></figure>

<h3 id="4-4-进入目标文件"><a href="#4-4-进入目标文件" class="headerlink" title="4.4 进入目标文件"></a>4.4 进入目标文件</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">cd</span> Python-3.8.8</span></span><br></pre></td></tr></table></figure>

<h3 id="4-5-配置安装路径：-usr-local-python3"><a href="#4-5-配置安装路径：-usr-local-python3" class="headerlink" title="4.5 配置安装路径：/usr/local/python3"></a>4.5 配置安装路径：/usr/local/python3</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 把python3.8.8 编译安装到/usr/<span class="built_in">local</span>/python38路径下</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: ./configure --prefix=/usr/<span class="built_in">local</span>/python38</span></span><br></pre></td></tr></table></figure>

<h3 id="4-6-编译并安装"><a href="#4-6-编译并安装" class="headerlink" title="4.6 编译并安装"></a>4.6 编译并安装</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: make &amp;&amp;  make install</span></span><br></pre></td></tr></table></figure>

<h3 id="4-7建立软连接：终端命令-python3，pip3"><a href="#4-7建立软连接：终端命令-python3，pip3" class="headerlink" title="4.7建立软连接：终端命令 python3，pip3"></a>4.7建立软连接：终端命令 python3，pip3</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: ln -s /usr/<span class="built_in">local</span>/python38/bin/python3 /usr/bin/python3.8</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: ln -s /usr/<span class="built_in">local</span>/python38/bin/pip3 /usr/bin/pip3.8</span></span><br></pre></td></tr></table></figure>

<h3 id="4-8-删除安装包与文件"><a href="#4-8-删除安装包与文件" class="headerlink" title="4.8 删除安装包与文件"></a>4.8 删除安装包与文件</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: rm -rf Python-3.8.8</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: rm -rf Python-3.8.8.tar.xz</span></span><br></pre></td></tr></table></figure>

<h2 id="5-安装uwsgi"><a href="#5-安装uwsgi" class="headerlink" title="5 安装uwsgi"></a>5 安装uwsgi</h2><h3 id="5-1-uwsgi-django运行"><a href="#5-1-uwsgi-django运行" class="headerlink" title="5.1 uwsgi+django运行"></a>5.1 uwsgi+django运行</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3.8 install uwsgi     # 用c写的web服务器，性能高，能抗高并发</span><br></pre></td></tr></table></figure>

<h3 id="5-2-会有一个uwsgi的可执行文件"><a href="#5-2-会有一个uwsgi的可执行文件" class="headerlink" title="5.2 会有一个uwsgi的可执行文件"></a>5.2 会有一个uwsgi的可执行文件</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ln -s /usr/local/python38/bin/uwsgi /usr/bin/uwsgi</span><br><span class="line"><span class="meta"></span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 以后跑项目不是使用python manage.py runserver 跑了,并发量太低（wsgiref）</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 而是使用  uwsgi -配置文件   跑</span></span><br></pre></td></tr></table></figure>

<h2 id="6-安装虚拟环境"><a href="#6-安装虚拟环境" class="headerlink" title="6 安装虚拟环境"></a>6 安装虚拟环境</h2><h3 id="6-1-安装依赖"><a href="#6-1-安装依赖" class="headerlink" title="6.1 安装依赖"></a>6.1 安装依赖</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;: pip3<span class="number">.8</span> install virtualenv</span><br><span class="line">&gt;: pip3<span class="number">.8</span> install virtualenvwrapper</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 升级 pip python3.8 -m pip install --upgrade pip</span></span><br></pre></td></tr></table></figure>

<h3 id="6-2-建立虚拟环境软连接"><a href="#6-2-建立虚拟环境软连接" class="headerlink" title="6.2 建立虚拟环境软连接"></a>6.2 建立虚拟环境软连接</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ln -s /usr/local/python38/bin/virtualenv /usr/bin/virtualenv</span><br></pre></td></tr></table></figure>

<h3 id="6-3-配置虚拟环境：填入下方内容"><a href="#6-3-配置虚拟环境：填入下方内容" class="headerlink" title="6.3 配置虚拟环境：填入下方内容"></a>6.3 配置虚拟环境：填入下方内容</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用vim打开</span></span><br><span class="line">&gt;: vim ~/.bash_profile</span><br><span class="line">    </span><br><span class="line"><span class="comment"># 配置</span></span><br><span class="line">VIRTUALENVWRAPPER_PYTHON=/usr/<span class="built_in">bin</span>/python3<span class="number">.8</span></span><br><span class="line">source /usr/local/python38/<span class="built_in">bin</span>/virtualenvwrapper.sh</span><br></pre></td></tr></table></figure>

<h3 id="6-4-退出编辑状态"><a href="#6-4-退出编辑状态" class="headerlink" title="6.4 退出编辑状态"></a>6.4 退出编辑状态</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: esc</span></span><br></pre></td></tr></table></figure>

<h3 id="6-5-保存修改并退出"><a href="#6-5-保存修改并退出" class="headerlink" title="6.5 保存修改并退出"></a>6.5 保存修改并退出</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;: :wq</span><br></pre></td></tr></table></figure>

<h3 id="6-6更新配置文件内容"><a href="#6-6更新配置文件内容" class="headerlink" title="6.6更新配置文件内容"></a>6.6更新配置文件内容</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">source</span> ~/.bash_profile</span></span><br></pre></td></tr></table></figure>

<h3 id="6-7-虚拟环境默认根目录："><a href="#6-7-虚拟环境默认根目录：" class="headerlink" title="6.7 虚拟环境默认根目录："></a>6.7 虚拟环境默认根目录：</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">~/.virtualenvs</span><br></pre></td></tr></table></figure>

<h3 id="6-8-创建虚拟环境"><a href="#6-8-创建虚拟环境" class="headerlink" title="6.8 创建虚拟环境"></a>6.8 创建虚拟环境</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mkvirtualenv -p python3<span class="number">.8</span> 项目环境名</span><br></pre></td></tr></table></figure>

<h2 id="7-安装Nginx-请求转发，动静分类"><a href="#7-安装Nginx-请求转发，动静分类" class="headerlink" title="7 安装Nginx (请求转发，动静分类)"></a>7 安装Nginx (请求转发，动静分类)</h2><h3 id="7-1-前往用户根目录"><a href="#7-1-前往用户根目录" class="headerlink" title="7.1 前往用户根目录"></a>7.1 前往用户根目录</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">cd</span> ~</span></span><br></pre></td></tr></table></figure>

<h3 id="7-2-下载nginx-1-13-7"><a href="#7-2-下载nginx-1-13-7" class="headerlink" title="7.2 下载nginx 1.13.7"></a>7.2 下载nginx 1.13.7</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: wget http://nginx.org/download/nginx-1.13.7.tar.gz</span></span><br></pre></td></tr></table></figure>

<h3 id="7-3-解压安装包"><a href="#7-3-解压安装包" class="headerlink" title="7.3 解压安装包"></a>7.3 解压安装包</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: tar -xf nginx-1.13.7.tar.gz</span></span><br></pre></td></tr></table></figure>

<h3 id="7-4-进入目标文件"><a href="#7-4-进入目标文件" class="headerlink" title="7.4 进入目标文件"></a>7.4 进入目标文件</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: <span class="built_in">cd</span> nginx-1.13.7</span></span><br></pre></td></tr></table></figure>

<h3 id="7-5-配置安装路径：-usr-local-nginx"><a href="#7-5-配置安装路径：-usr-local-nginx" class="headerlink" title="7.5 配置安装路径：/usr/local/nginx"></a>7.5 配置安装路径：/usr/local/nginx</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: ./configure --prefix=/usr/<span class="built_in">local</span>/nginx</span></span><br></pre></td></tr></table></figure>

<h3 id="7-6-编译并安装"><a href="#7-6-编译并安装" class="headerlink" title="7.6 编译并安装"></a>7.6 编译并安装</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: make &amp;&amp; sudo make install</span></span><br></pre></td></tr></table></figure>

<h3 id="7-7-建立软连接：终端命令-nginx"><a href="#7-7-建立软连接：终端命令-nginx" class="headerlink" title="7.7 建立软连接：终端命令 nginx"></a>7.7 建立软连接：终端命令 nginx</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: ln -s /usr/<span class="built_in">local</span>/nginx/sbin/nginx /usr/bin/nginx</span></span><br></pre></td></tr></table></figure>

<h3 id="7-8-删除安装包与文件："><a href="#7-8-删除安装包与文件：" class="headerlink" title="7.8 删除安装包与文件："></a>7.8 删除安装包与文件：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&gt;: cd ~</span><br><span class="line">&gt;: rm -rf nginx-<span class="number">1.13</span><span class="number">.7</span></span><br><span class="line">&gt;: rm -rf nginx-<span class="number">1.13</span><span class="number">.7</span>.tar.xz</span><br></pre></td></tr></table></figure>

<h3 id="7-9测试Nginx环境，服务器运行nginx，本地访问服务器ip"><a href="#7-9测试Nginx环境，服务器运行nginx，本地访问服务器ip" class="headerlink" title="7.9测试Nginx环境，服务器运行nginx，本地访问服务器ip"></a>7.9测试Nginx环境，服务器运行nginx，本地访问服务器ip</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;</span><span class="bash">: nginx</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: 服务器绑定的域名 或 ip:80</span></span><br></pre></td></tr></table></figure>

<h3 id="7-10-nginx-常用命令"><a href="#7-10-nginx-常用命令" class="headerlink" title="7.10  nginx 常用命令"></a>7.10  nginx 常用命令</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">1）启动</span><br><span class="line">    &gt;: nginx</span><br><span class="line">    &gt;: ps aux |grep nginx</span><br><span class="line"></span><br><span class="line">2）关闭nginx</span><br><span class="line">    &gt;: nginx -s stop</span><br><span class="line"></span><br><span class="line">3）重启nginx</span><br><span class="line">    &gt;: nginx -s reload</span><br><span class="line"></span><br><span class="line">4）查看端口，强行关闭</span><br><span class="line">    &gt;: ps -aux|grep nginx</span><br><span class="line">    &gt;: kill &lt;pid:进程编号&gt;</span><br></pre></td></tr></table></figure>

<h2 id="8-配置前端项目，上线部署"><a href="#8-配置前端项目，上线部署" class="headerlink" title="8 配置前端项目，上线部署"></a>8 配置前端项目，上线部署</h2><h3 id="8-1-把setting-js中的后端路径改成公网地址"><a href="#8-1-把setting-js中的后端路径改成公网地址" class="headerlink" title="8.1 把setting.js中的后端路径改成公网地址"></a>8.1 把setting.js中的后端路径改成公网地址</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">export  default &#123;</span><br><span class="line">    base_url:&#x27;http://8.130.176.65:8000/api/v1/&#x27;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="8-2-把vue项目编译成纯静态"><a href="#8-2-把vue项目编译成纯静态" class="headerlink" title="8.2 把vue项目编译成纯静态"></a>8.2 把vue项目编译成纯静态</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm run build</span><br></pre></td></tr></table></figure>

<h3 id="8-3-在服务器上安装"><a href="#8-3-在服务器上安装" class="headerlink" title="8.3 在服务器上安装"></a>8.3 在服务器上安装</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">yum install  -y lrzsz  </span><br><span class="line">按住文件，拖到服务器即可</span><br><span class="line"><span class="meta">#</span><span class="bash"> 使用其他ftp软件上传</span></span><br></pre></td></tr></table></figure>

<h3 id="8-4-解压"><a href="#8-4-解压" class="headerlink" title="8.4 解压"></a>8.4 解压</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">yum install unzip -y</span><br><span class="line">unzip dist.zip </span><br><span class="line"></span><br><span class="line">mkdir /home/html</span><br><span class="line">mv ~/dist /home/html</span><br></pre></td></tr></table></figure>

<h3 id="8-5-配置nginx，代理静态文件"><a href="#8-5-配置nginx，代理静态文件" class="headerlink" title="8.5 配置nginx，代理静态文件"></a>8.5 配置nginx，代理静态文件</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">cd /usr/local/nginx/conf</span><br><span class="line"><span class="meta">#</span><span class="bash"> nginx.conf nginx 的配置文件</span></span><br><span class="line">mv nginx.conf nginx.conf.bak</span><br><span class="line">vi nginx.conf   # 写入下面</span><br><span class="line"></span><br><span class="line">events &#123;</span><br><span class="line">    worker_connections  1024;</span><br><span class="line">&#125;</span><br><span class="line">http &#123;</span><br><span class="line">    include       mime.types;</span><br><span class="line">    default_type  application/octet-stream;</span><br><span class="line">    sendfile        on;</span><br><span class="line">    server &#123;</span><br><span class="line">        listen 80;</span><br><span class="line">        server_name  127.0.0.1;</span><br><span class="line">        charset utf-8;</span><br><span class="line">        location / &#123;</span><br><span class="line">            root /home/html/dist; # html访问路径</span><br><span class="line">            index index.html; # html文件名称</span><br><span class="line">            try_files $uri $uri/ /index.html; # 解决单页面应用刷新404问题</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<h3 id="8-6-重启nginx即可"><a href="#8-6-重启nginx即可" class="headerlink" title="8.6 重启nginx即可"></a>8.6 重启nginx即可</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">nginx -s stop</span><br><span class="line">niginx</span><br></pre></td></tr></table></figure>

<h3 id="8-7-访问IP就能看到前端"><a href="#8-7-访问IP就能看到前端" class="headerlink" title="8.7 访问IP就能看到前端"></a>8.7 访问IP就能看到前端</h3><h2 id="9-配置后台项目，部署"><a href="#9-配置后台项目，部署" class="headerlink" title="9 配置后台项目，部署"></a>9 配置后台项目，部署</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 项目在服务器上运行，关于migrations要不要提交的问题</span></span><br><span class="line">	-如果提交：好处是可以看到开发阶段所有的表变化情况</span><br><span class="line">    -如果不提交：服务端自己维护一套迁移变化，不会出冲突</span><br></pre></td></tr></table></figure>

<h3 id="9-1-项目依赖库"><a href="#9-1-项目依赖库" class="headerlink" title="9.1 项目依赖库"></a>9.1 项目依赖库</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">-放在项目根路径下：requirements.txt</span><br><span class="line">   -pip list   # 当前环境安装了哪些模块</span><br><span class="line">   -pip freeze &gt; requirements.txt # 把当前虚拟环境中所的依赖，写入到requirements.txt</span><br></pre></td></tr></table></figure>

<h3 id="9-2-在服务器上，把后端项目拉下来"><a href="#9-2-在服务器上，把后端项目拉下来" class="headerlink" title="9.2 在服务器上，把后端项目拉下来"></a>9.2 在服务器上，把后端项目拉下来</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mkdir /home/project</span><br><span class="line">cd /home/project</span><br><span class="line">git clone https://gitee.com/liuqingzheng/luffy_api.git</span><br></pre></td></tr></table></figure>

<h3 id="9-3-创建虚拟环境，在虚拟环境中，把所有依赖装好"><a href="#9-3-创建虚拟环境，在虚拟环境中，把所有依赖装好" class="headerlink" title="9.3 创建虚拟环境，在虚拟环境中，把所有依赖装好"></a>9.3 创建虚拟环境，在虚拟环境中，把所有依赖装好</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">workon luffy</span><br><span class="line">pip install -r requirements.txt</span><br><span class="line"><span class="meta">#</span><span class="bash"> mysqlclient装不上</span></span><br><span class="line">yum install mysql-devel</span><br><span class="line">yum install python-devel</span><br><span class="line">pip install mysqlclient</span><br><span class="line">pip install -r requirements.txt</span><br><span class="line">pip install uwsgi   # 在正式环境和虚拟环境都要装一下uwsgi</span><br></pre></td></tr></table></figure>

<h3 id="9-4-配置数据库"><a href="#9-4-配置数据库" class="headerlink" title="9.4 配置数据库"></a>9.4 配置数据库</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">1）管理员连接数据库</span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: mysql -uroot -pLqz1234?</span></span><br><span class="line"></span><br><span class="line">2）创建数据库</span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: create database luffy default charset=utf8;</span></span><br><span class="line"></span><br><span class="line">3）设置权限账号密码：账号密码要与项目中配置的一致</span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: grant all privileges on luffy.* to <span class="string">&#x27;luffynew&#x27;</span>@<span class="string">&#x27;%&#x27;</span> identified by <span class="string">&#x27;Luffy123?&#x27;</span>;</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: grant all privileges on luffy.* to <span class="string">&#x27;luffynew&#x27;</span>@<span class="string">&#x27;localhost&#x27;</span> identified by <span class="string">&#x27;Luffy123?&#x27;</span>;</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: flush privileges;</span></span><br><span class="line"></span><br><span class="line">4）退出mysql</span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: quit;</span></span><br></pre></td></tr></table></figure>

<h3 id="9-5-迁移命令"><a href="#9-5-迁移命令" class="headerlink" title="9.5 迁移命令"></a>9.5 迁移命令</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">python manage_pro.py makemigrations</span><br><span class="line">python manage_pro.py migrate</span><br></pre></td></tr></table></figure>

<h3 id="9-6-使用uwsgi-django运行项目"><a href="#9-6-使用uwsgi-django运行项目" class="headerlink" title="9.6 使用uwsgi+django运行项目"></a>9.6 使用uwsgi+django运行项目</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 先用python manage_pro.py runserver 0.0.0.0:8000 跑一下试试</span></span><br></pre></td></tr></table></figure>

<h3 id="9-7写uwsgi的配置文件，项目根路径"><a href="#9-7写uwsgi的配置文件，项目根路径" class="headerlink" title="9.7写uwsgi的配置文件，项目根路径"></a>9.7写uwsgi的配置文件，项目根路径</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> vim luffy.xml</span></span><br><span class="line">&lt;uwsgi&gt;</span><br><span class="line">   &lt;socket&gt;127.0.0.1:8080&lt;/socket&gt;</span><br><span class="line">   &lt;chdir&gt;/home/project/luffy_api&lt;/chdir&gt;         </span><br><span class="line">   &lt;module&gt;luffy_api.wsgi&lt;/module&gt;</span><br><span class="line">   &lt;processes&gt;4&lt;/processes&gt;</span><br><span class="line">   &lt;daemonize&gt;uwsgi.log&lt;/daemonize&gt;</span><br><span class="line">&lt;/uwsgi&gt;</span><br></pre></td></tr></table></figure>

<h3 id="9-8启动uwsgi"><a href="#9-8启动uwsgi" class="headerlink" title="9.8启动uwsgi"></a>9.8启动uwsgi</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">uwsgi -x ./luffy.xml</span><br><span class="line">ps aux |grep uwsgi</span><br></pre></td></tr></table></figure>

<h3 id="9-9-关闭uwsgi"><a href="#9-9-关闭uwsgi" class="headerlink" title="9.9 关闭uwsgi"></a>9.9 关闭uwsgi</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pkill -9 uwsgi</span><br></pre></td></tr></table></figure>

<h3 id="9-10配置nginx转发给uwsgi"><a href="#9-10配置nginx转发给uwsgi" class="headerlink" title="9.10配置nginx转发给uwsgi"></a>9.10配置nginx转发给uwsgi</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">server &#123;</span><br><span class="line">       listen 8000;</span><br><span class="line">       server_name  127.0.0.1;</span><br><span class="line">       charset utf-8;</span><br><span class="line">       location / &#123;</span><br><span class="line">          include uwsgi_params;</span><br><span class="line">          uwsgi_pass 127.0.0.1:8080;  # 端口要和uwsgi里配置的一样</span><br><span class="line">          uwsgi_param UWSGI_SCRIPT luffy_api.wsgi;  #wsgi.py所在的目录名+.wsgi</span><br><span class="line">          uwsgi_param UWSGI_CHDIR /home/project/luffy_api/; # 项目路径</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h3 id="9-11-查看端口被哪个进程监听"><a href="#9-11-查看端口被哪个进程监听" class="headerlink" title="9.11 查看端口被哪个进程监听"></a>9.11 查看端口被哪个进程监听</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">netstat -nlp|grep 80</span><br></pre></td></tr></table></figure>

<h3 id="9-12-导入测试数据"><a href="#9-12-导入测试数据" class="headerlink" title="9.12 导入测试数据"></a>9.12 导入测试数据</h3><h3 id="9-13-后台管理，动静分离"><a href="#9-13-后台管理，动静分离" class="headerlink" title="9.13 后台管理，动静分离"></a>9.13 后台管理，动静分离</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash">修改线上的pro.py 配置文件，加入</span></span><br><span class="line">STATIC_ROOT = &#x27;/home/project/luffy_api/luffy_api/static&#x27;  </span><br><span class="line">STATICFILES_DIRS = (os.path.join(BASE_DIR, &quot;static&quot;),)</span><br><span class="line"><span class="meta">#</span><span class="bash"> 创建文件夹</span></span><br><span class="line"><span class="meta">&gt;</span><span class="bash">: mkdir /home/project/luffy_api/luffy_api/static</span></span><br><span class="line"><span class="meta"></span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 完成静态文件迁移（把静态的js，css都收集到，上面那个文件夹下）</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 前后端混合的项目必须这么做</span></span><br><span class="line">python manage_pro.py collectstatic</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="9-14-使用nginx代理"><a href="#9-14-使用nginx代理" class="headerlink" title="9.14 使用nginx代理"></a>9.14 使用nginx代理</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"> #</span><span class="bash"> 新增的配置静态文件</span></span><br><span class="line">location /static &#123;</span><br><span class="line">    alias /home/project/luffy_api/luffy_api/static;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="9-15-重启nginx即可"><a href="#9-15-重启nginx即可" class="headerlink" title="9.15 重启nginx即可"></a>9.15 重启nginx即可</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">nginx -s reload</span><br></pre></td></tr></table></figure>

<h3 id="9-16-项目根路径下启异步任务"><a href="#9-16-项目根路径下启异步任务" class="headerlink" title="9.16 项目根路径下启异步任务"></a>9.16 项目根路径下启异步任务</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">celery -A xx  worker -l info</span><br><span class="line">celery -A xx  beat -l info</span><br></pre></td></tr></table></figure>

<h3 id="9-17-项目连接上域名"><a href="#9-17-项目连接上域名" class="headerlink" title="9.17 项目连接上域名"></a>9.17 项目连接上域名</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1 买一个域名：</span><br><span class="line">2 在阿里云的域名解析配置一下</span><br></pre></td></tr></table></figure>




      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-MySQL安装" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/MySQL%E5%AE%89%E8%A3%85/" class="article-date">
      <time datetime="2021-11-23T04:55:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/MySQL%E5%AE%89%E8%A3%85/">MySQL数据库</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h1 id="MySQL数据库。"><a href="#MySQL数据库。" class="headerlink" title="MySQL数据库。"></a>MySQL数据库。</h1><p>以前，在开发程序时，我们会把很多的数据和信息存储到某个文件夹中的文件中，例如：user.txt 、db.xlsx 等。</p>
<p>现在，有那么一个叫：数据库管理系统（DBMS，Database Management System）的软件，可以帮助我们实现对文件夹中的文件进行操作，而我们只要学习DBMS能识别的指令， 就能控制它去帮助我们实现的文件和文件夹的处理。例如：</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210507211911641.png"></p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508090834860.png" alt="image-20210508090834860"></p>
<p>数据库管理系统（DBMS）专注于帮助开发者解决数据存储的问题，这样开发者就可以把主要精力放在实现业务功能上了。</p>
<p>业内有很多的的数据库管理系统产品，例如：</p>
<ul>
<li><strong>MySQL</strong>，原来是sun公司，后来被甲骨文收购。现在互联网企业几乎都在使用。【免费 + 收费】</li>
<li>Oracle，甲骨文。收费，一般国企、事业单位居多。【收费】</li>
<li>Microsoft SQL Server，微软。【收费】</li>
<li>DB2，IBM。【免费 + 收费】</li>
<li>SQLite，D. Richard Hipp个人开发。【免费】</li>
<li>Access， 微软。【收费】</li>
<li>PostgreSQL，加州大学伯克利分校。【免费】</li>
<li>等众多..</li>
</ul>
<p>由于各大公司都是使用MySQL，所以我们课程主要给大家讲解MySQL数据库。</p>
<p>在项目开发中想要基于MySQL来进行数据存储，大致应该怎么做呢？</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508102020237.png" alt="image-20210508102020237"></p>
<p>本系列的MySQL模块会分为5部分来讲解：</p>
<ul>
<li>MySQL入门，安装和快速应用Python实现数据库的操作。</li>
<li>必备SQL和授权，学习更多必备的指令让数据库实现更多业务场景。</li>
<li>SQL强化和实践，强化练习必备”指令“（项目开发写的最多）。</li>
<li>索引和函数以及存储过程，掌握常见性能提升手段以及那些应用不是很频繁却又需了解的知识点。</li>
<li>Python操作MySQL和应用，侧重点在于Python开发，让大家了解Python开发中必备的实战应用，例如：锁、事务、数据库连接池等。</li>
</ul>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210528190629407.png" alt="image-20210528190629407"></p>
<h1 id="MySQL入门"><a href="#MySQL入门" class="headerlink" title="MySQL入门"></a>MySQL入门</h1><p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210528192555988.png" alt="image-20210528192555988"></p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508102020237.png" alt="image-20210508102020237"></p>
<p>课程目标：学习安装和快速应用Python实现数据库的操作。</p>
<p>课程概要：</p>
<ul>
<li>安装 &amp; 配置 &amp; 启动<ul>
<li>win</li>
<li>mac</li>
</ul>
</li>
<li>数据库 管理（类比文件夹）</li>
<li>表 管理        （类比文件夹下的Excel文件）</li>
<li>数据行 管理（类比Excel文件中的数据行）</li>
<li>Python操作MySQL及相关安全的问题</li>
</ul>
<h2 id="1-安装-amp-配置-amp-启动"><a href="#1-安装-amp-配置-amp-启动" class="headerlink" title="1. 安装 &amp; 配置 &amp; 启动"></a>1. 安装 &amp; 配置 &amp; 启动</h2><p>MySQL现在的版本主要分为：</p>
<ul>
<li>5.x 版本，现在互联网企业中的主流版本，包括：头条、美图、百度、腾讯等互联网公司主流的版本。</li>
<li>8.x 版本，新增了一些了窗口函数、持久化配置、隐藏索引等其他功能。</li>
</ul>
<p>所以，我们课程会以常用大版本中最新的版本为例来讲解，即：5.7.31 （依然有很多企业在用5.6.x，但新项目基本上都是5.7.x了）。</p>
<h3 id="1-1-win系统"><a href="#1-1-win系统" class="headerlink" title="1.1 win系统"></a>1.1 win系统</h3><h4 id="第1步：下载安装"><a href="#第1步：下载安装" class="headerlink" title="第1步：下载安装"></a>第1步：下载安装</h4><p><a target="_blank" rel="noopener" href="https://downloads.mysql.com/archives/community/">https://downloads.mysql.com/archives/community/</a></p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508103751068.png" alt="image-20210508103751068"></p>
<h4 id="第2步：解压至任意文件夹"><a href="#第2步：解压至任意文件夹" class="headerlink" title="第2步：解压至任意文件夹"></a>第2步：解压至任意文件夹</h4><p>建议解压至软件安装目录，例如：</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508105417186.png" alt="image-20210508105417186"></p>
<h4 id="第3步：创建配置文件"><a href="#第3步：创建配置文件" class="headerlink" title="第3步：创建配置文件"></a>第3步：创建配置文件</h4><p>在MySQL的安装目录下创建 <code>my.ini</code> 的文件，作为MySQL的配置文件。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508120708175.png" alt="image-20210508120708175"></p>
<p>其实，MySQL的配置文件可以放在很多的目录，下图是配置文件的优先级：</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510150530193.png" alt="image-20210510150530193"></p>
<p>强烈，建议大家还是把配置文件放在MySQL安装目录下，这样以后电脑上想要安装多个版本的MySQL时，配置文件可以相互独立不影响。</p>
<p>注意：如果你电脑的上述其他目录存在MySQL配置文件，建议删除，否则可能会影响MySQL的启动。</p>
<h4 id="第4步：初始化"><a href="#第4步：初始化" class="headerlink" title="第4步：初始化"></a>第4步：初始化</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; &quot;C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe&quot;  --initialize-insecure</span><br></pre></td></tr></table></figure>

<p>初始化命令在执行时，会自动读取配置文件并执行初始化，此过程主要会做两件事：</p>
<ul>
<li>自动创建data目录，以后我们的数据都会存放在这个目录。</li>
<li>同时创建建必备一些的数据，例如默认账户 root （无密码），用于登录MySQL并通过指令操作MySQL。</li>
</ul>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510151829891.png" alt="image-20210510151829891"></p>
<p>在windowns安装过程中如果有报错 （ msvcr120.dll不存在 ），请下载并安装下面的两个补丁：</p>
<ul>
<li>vcredist：<a target="_blank" rel="noopener" href="https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=40784">https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=40784</a>  （主要）</li>
</ul>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508115414183.png"></p>
<ul>
<li>dirctx：<a target="_blank" rel="noopener" href="https://www.microsoft.com/zh-CN/download/details.aspx?id=35">https://www.microsoft.com/zh-CN/download/details.aspx?id=35</a><img src="assets/image-20210508115521913.png" alt="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508115521913.png" style="zoom: 33%;" /></li>
</ul>
<h4 id="第5步：启动"><a href="#第5步：启动" class="headerlink" title="第5步：启动"></a>第5步：启动</h4><p>启动MySQL常见的有两种方式：</p>
<ul>
<li><p>临时启动</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="string">&quot;C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe&quot;</span></span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510152448745.png" alt="image-20210510152448745"></p>
<p>注意：此时程序会挂起，内部就是可以接收客户端发来的MySQL指令，关闭窗口或Ctrl+c 就可以停止运行。</p>
<p>这种启动方式每次开机或想要开启都需要手动执行一遍命令比较麻烦。</p>
</li>
<li><p>制作windows服务，基于windows服务管理。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt;<span class="string">&quot;C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe&quot;</span> --install mysql57</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510152702489.png" alt="image-20210510152702489"></p>
<p>创建好服务之后，可以通过命令 启动和关闭服务，例如：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; net start mysql57</span><br><span class="line">&gt;&gt;&gt; net stop mysql57</span><br></pre></td></tr></table></figure>

<p>也可以在window的服务管理中点击按钮启动和关闭服务。例如：</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210529225011045.png" alt="image-20210529225011045"></p>
<p><img src="assets/image-20210529225043126.png" alt="image-20210529225043126"></p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510152740268.png" alt="image-20210510152740268"></p>
<p>以后不再想要使用window服务了，也可以将制作的这个MySQL服务删除。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt;&quot;C:\Program Files\mysql-5.7.31-winx64\bin\mysqld.exe&quot; --remove mysql57</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510152809233.png" alt="image-20210510152809233"></p>
</li>
</ul>
<h4 id="第6步：测试连接MySQL"><a href="#第6步：测试连接MySQL" class="headerlink" title="第6步：测试连接MySQL"></a>第6步：测试连接MySQL</h4><p>安装并启动MySQL之后，就可以连接MySQL来测试是否已正确安装并启动成功。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510153336093.png" alt="image-20210510153336093"></p>
<p>以后在开发时，肯定是要用Python代码来连接MySQL并且进行数据操作（后面讲）。</p>
<p>在安装MySQL时，其实也自动安装了一个工具（客户端），让我们快速实现连接MySQL并发送指令。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510154446628.png" alt="image-20210510154446628"></p>
<p>注意：如果把bin目录加入环境变量，每次在运行命令时，就不用再重新输入绝对路径了。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210529225251803.png" alt="image-20210529225251803"></p>
<p>上述过程如果操作完成之后，证明你的安装和启动过程就搞定了。</p>
<h3 id="1-2-mac系统"><a href="#1-2-mac系统" class="headerlink" title="1.2 mac系统"></a>1.2 mac系统</h3><p>mac系统和win不同，MySQL为他提供了非常方便的一站式安装程序，只要点击、next就可以安装、初始化完成。</p>
<h4 id="第1步：安装和初始化"><a href="#第1步：安装和初始化" class="headerlink" title="第1步：安装和初始化"></a>第1步：安装和初始化</h4><p><a target="_blank" rel="noopener" href="https://downloads.mysql.com/archives/community/">https://downloads.mysql.com/archives/community/</a></p>
<img src="assets/image-20210508103830229.png" alt="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508103830229.png"  />

<img src="assets/image-20210508165414794.png" alt="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508165414794.png" style="zoom:50%;" />



<img src="assets/image-20210508171059416.png" alt="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508171059416.png" style="zoom:50%;" />



<p>这个基于dmg文件的安装过程，其实包含了：</p>
<ul>
<li>安装，默认安装在了 <code>/usr/local/mysql-5.7.31-macos10.14-x86_64/</code>目录。</li>
<li>初始化，在安装目录下创建data目录用于存放数据； 初始化模块数据库以及账户相关等，例如： 账cd</li>
</ul>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510103342842.png" alt="image-20210510103342842"></p>
<h4 id="第2步：创建配置文件"><a href="#第2步：创建配置文件" class="headerlink" title="第2步：创建配置文件"></a>第2步：创建配置文件</h4><p>建议在MySQL安装目录下创建 <code>etc/my.cnf</code> 作为MySQL的配置文件。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510161700478.png" alt="image-20210510161700478"></p>
<p>MySQL的配置文件按照优先级，会在以下目录中寻找：</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510161845843.png" alt="image-20210510161845843"></p>
<p>为了避免多个版本共存时，配置文件混乱的问题，建议大家还是把配置文件放在当前MySQL的安装目录下。</p>
<h4 id="第3步：启动"><a href="#第3步：启动" class="headerlink" title="第3步：启动"></a>第3步：启动</h4><p>在Mac系统中启动MySQL常见的有2种方式：</p>
<ul>
<li><p>安装目录中自带 <code>mysql.server</code> 脚本（建议）</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">sudo /usr/local/mysql/support-files/mysql.server start</span><br><span class="line"><span class="comment"># 输入电脑密码</span></span><br><span class="line"></span><br><span class="line">sudo mysql.server start</span><br><span class="line"><span class="comment"># 输入电脑密码</span></span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo /usr/local/mysql/support-files/mysql.server stop</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510162854578.png" alt="image-20210510162854578"></p>
</li>
</ul>
<p>  为了避免每次执行命令都需要些路径，可以将路径 <code>/usr/local/mysql/support-files</code>加入到环境变量中。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510165107737.png" alt="image-20210510165107737"></p>
<p>  操作完成之后，再在终端执行下命令：<code>source ~/.zprofile</code> 让设置的环境变量立即生效。</p>
<p>  注意：mac系统的版本如果比较老，会显示空白的 <code>zprofile</code> 文件，此就要去打开   <code>bash_profile</code> 文件。</p>
<p>  这样设置好之后，以后就可以使用下面的命令去启动和关闭MySQL了。</p>
  <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sudo mysql.server start</span><br><span class="line">sudo mysql.server stop</span><br></pre></td></tr></table></figure>

<ul>
<li>系统偏好设置（不推荐）</li>
</ul>
<img src="assets/image-20210510104009559.png" alt="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510104009559.png" style="zoom: 33%;" />





<p>第一种<code>mysql.server</code>脚本的形式，内部是使用 <code>mysqld_safe</code>运行，可以守护我们的MySQL进程，如意外挂掉可自动重启。</p>
<h4 id="第4步：测试连接MySQL"><a href="#第4步：测试连接MySQL" class="headerlink" title="第4步：测试连接MySQL"></a>第4步：测试连接MySQL</h4><p>安装并启动MySQL之后，就可以连接MySQL来测试是否已正确安装并启动成功。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510153336093.png" alt="image-20210510153336093"></p>
<p>以后在开发时，肯定是要用Python代码来连接MySQL并且进行数据操作（后面讲）。</p>
<p>在安装MySQL时，其实也自动安装了一个工具（客户端），让我们快速实现连接MySQL并发送指令。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510171029083.png" alt="image-20210510171029083"></p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510171004699.png" alt="image-20210510171004699"></p>
<p>注意：<code>/usr/local/mysql/bin</code>也可以加入到环境变量。</p>
<p>至此，在Mac系统中关于MySQL的安装和配置就完成了。</p>
<h3 id="1-3-关于配置文件"><a href="#1-3-关于配置文件" class="headerlink" title="1.3 关于配置文件"></a>1.3 关于配置文件</h3><p>上述的过程中，我们在配置文件中只添加了很少的配置。</p>
<p>其实，配置项有很多，而哪些配置项都有默认值，如果我们不配置，MySQL则自动使用默认值。</p>
<h3 id="1-4-关于密码"><a href="#1-4-关于密码" class="headerlink" title="1.4 关于密码"></a>1.4 关于密码</h3><h4 id="1-设置和修改root密码"><a href="#1-设置和修改root密码" class="headerlink" title="1. 设置和修改root密码"></a>1. 设置和修改root密码</h4><p>在windows系统中模块默认 root 账户是没有密码的，如果想要为账户设定密码，可以在利用root账户登录成功之后，执行：</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210530001548192.png" alt="image-20210530001548192"></p>
<h4 id="2-忘记root密码"><a href="#2-忘记root密码" class="headerlink" title="2. 忘记root密码"></a>2. 忘记root密码</h4><p>如果你忘记了MySQL账户的密码。</p>
<ul>
<li><p>修改配置文件，在 [mysqld] 节点下添加 <code>skip-grant-tables=1</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[mysqld]</span><br><span class="line">...</span><br><span class="line">skip-grant-tables=1</span><br><span class="line">...</span><br></pre></td></tr></table></figure></li>
<li><p>重启MySQL，再次登录时，不需要密码直接可以进去了</p>
<ul>
<li><p>windows重启</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">net stop mysql57</span><br><span class="line">net start mysql57</span><br></pre></td></tr></table></figure></li>
<li><p>mac重启</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sudo mysql.server restart</span><br></pre></td></tr></table></figure></li>
</ul>
<p>重启后，无序密码就可以进入。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; mysql -u root -p</span><br></pre></td></tr></table></figure></li>
<li><p>进入数据库后执行修改密码命令</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">use mysql;</span><br><span class="line">update user set authentication_string = password(&#x27;新密码&#x27;),password_last_changed=now() where user=&#x27;root&#x27;;</span><br></pre></td></tr></table></figure></li>
<li><p>退出并再次修改配置文件，删除 [mysqld] 节点下的 <code>skip-grant-tables=1</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[mysqld]</span><br><span class="line">...</span><br><span class="line"># skip-grant-tables=1</span><br><span class="line">...</span><br></pre></td></tr></table></figure></li>
<li><p>再次重启，以后就可以使用新密码登录了。</p>
</li>
</ul>
<h2 id="2-数据库-管理"><a href="#2-数据库-管理" class="headerlink" title="2. 数据库 管理"></a>2. 数据库 管理</h2><p>安装上数据库之后，就需要开始学习指令了，通过指令让MySQL去做出一些文件操作。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210507211911641.png" alt="image-20210507211911641"></p>
<p>如果将数据库管理系统与之前的文件管理做类比的话：</p>
<table>
<thead>
<tr>
<th>数据库管理系统</th>
<th>文件管理</th>
</tr>
</thead>
<tbody><tr>
<td>数据库</td>
<td>文件夹</td>
</tr>
<tr>
<td>数据表</td>
<td>文件夹下的excel文件</td>
</tr>
</tbody></table>
<p>接下来，我们先学习 数据库（文件夹）相关操作的指令。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510153336093.png" alt="image-20210510153336093"></p>
<h3 id="2-1-内置客户端操作"><a href="#2-1-内置客户端操作" class="headerlink" title="2.1 内置客户端操作"></a>2.1 内置客户端操作</h3><p>当连接上MySQL之后，执行如下指令（一般称为SQL语句），就可以对MySQL的数据进行操作。</p>
<ul>
<li><p>查看当前所有的数据库：  <code>show databases;</code></p>
</li>
<li><p>创建数据库：<code>create database 数据库名 DEFAULT CHARSET utf8 COLLATE utf8_general_ci;</code> </p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">create database day25db;</span><br><span class="line"></span><br><span class="line">create database day25db DEFAULT CHARSET utf8 COLLATE utf8_general_ci;</span><br></pre></td></tr></table></figure></li>
<li><p>删除数据库：<code>drop database 数据库名</code>;</p>
</li>
<li><p>进入数据（进入文件）：<code>use 数据库;</code></p>
</li>
</ul>
<p>示例：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 1.登录MySQL</span></span><br><span class="line">wupeiqi@wupeiqideMBP ~ % /usr/<span class="built_in">local</span>/mysql/bin/mysql -u root -p</span><br><span class="line">Enter password:</span><br><span class="line">Welcome to the MySQL monitor.  Commands end with ; or \g.</span><br><span class="line">Your MySQL connection id is 5</span><br><span class="line">Server version: 5.7.31 MySQL Community Server (GPL)</span><br><span class="line"></span><br><span class="line">Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.</span><br><span class="line"></span><br><span class="line">Oracle is a registered trademark of Oracle Corporation and/or its</span><br><span class="line">affiliates. Other names may be trademarks of their respective</span><br><span class="line">owners.</span><br><span class="line"></span><br><span class="line">Type <span class="string">&#x27;help;&#x27;</span> or <span class="string">&#x27;\h&#x27;</span> <span class="keyword">for</span> <span class="built_in">help</span>. Type <span class="string">&#x27;\c&#x27;</span> to clear the current input statement.</span><br><span class="line"></span><br><span class="line"><span class="comment"># 2.查看当前数据库</span></span><br><span class="line">mysql&gt; show databases;</span><br><span class="line">+--------------------+</span><br><span class="line">| Database           |</span><br><span class="line">+--------------------+</span><br><span class="line">| information_schema |</span><br><span class="line">| mysql              |</span><br><span class="line">| performance_schema |</span><br><span class="line">| sys                |</span><br><span class="line">+--------------------+</span><br><span class="line">4 rows <span class="keyword">in</span> <span class="built_in">set</span> (0.00 sec)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 创建数据库:  create database 数据库名 default charset 编码 collate 排序规则;</span></span><br><span class="line">mysql&gt; create database db1 default charset utf8 collate utf8_general_ci;</span><br><span class="line">Query OK, 1 row affected (0.00 sec)</span><br><span class="line"></span><br><span class="line">mysql&gt; show databases;</span><br><span class="line">+--------------------+</span><br><span class="line">| Database           |</span><br><span class="line">+--------------------+</span><br><span class="line">| information_schema |</span><br><span class="line">| db1                |</span><br><span class="line">| mysql              |</span><br><span class="line">| performance_schema |</span><br><span class="line">| sys                |</span><br><span class="line">+--------------------+</span><br><span class="line">5 rows <span class="keyword">in</span> <span class="built_in">set</span> (0.01 sec)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 4. 删除数据库</span></span><br><span class="line">mysql&gt; drop database db1;</span><br><span class="line">Query OK, 0 rows affected (0.00 sec)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 5. 查看当前数据库</span></span><br><span class="line">mysql&gt; show databases;</span><br><span class="line">+--------------------+</span><br><span class="line">| Database           |</span><br><span class="line">+--------------------+</span><br><span class="line">| information_schema |</span><br><span class="line">| mysql              |</span><br><span class="line">| performance_schema |</span><br><span class="line">| sys                |</span><br><span class="line">+--------------------+</span><br><span class="line">4 rows <span class="keyword">in</span> <span class="built_in">set</span> (0.00 sec)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 6. 进入数据库</span></span><br><span class="line">mysql&gt; use mysql;</span><br><span class="line">Reading table information <span class="keyword">for</span> completion of table and column names</span><br><span class="line">You can turn off this feature to get a quicker startup with -A</span><br><span class="line"></span><br><span class="line">Database changed</span><br><span class="line"><span class="comment"># 7. 进入mysql数据库（文件夹），查看此数据库下的所有表。</span></span><br><span class="line">mysql&gt; show tables;</span><br><span class="line">+---------------------------+</span><br><span class="line">| Tables_in_mysql           |</span><br><span class="line">+---------------------------+</span><br><span class="line">| columns_priv              |</span><br><span class="line">| db                        |</span><br><span class="line">| engine_cost               |</span><br><span class="line">| event                     |</span><br><span class="line">| func                      |</span><br><span class="line">| general_log               |</span><br><span class="line">| gtid_executed             |</span><br><span class="line">| help_category             |</span><br><span class="line">| help_keyword              |</span><br><span class="line">| help_relation             |</span><br><span class="line">| help_topic                |</span><br><span class="line">| innodb_index_stats        |</span><br><span class="line">| innodb_table_stats        |</span><br><span class="line">| ndb_binlog_index          |</span><br><span class="line">| plugin                    |</span><br><span class="line">| proc                      |</span><br><span class="line">| procs_priv                |</span><br><span class="line">| proxies_priv              |</span><br><span class="line">| server_cost               |</span><br><span class="line">| servers                   |</span><br><span class="line">| slave_master_info         |</span><br><span class="line">| slave_relay_log_info      |</span><br><span class="line">| slave_worker_info         |</span><br><span class="line">| slow_log                  |</span><br><span class="line">| tables_priv               |</span><br><span class="line">| time_zone                 |</span><br><span class="line">| time_zone_leap_second     |</span><br><span class="line">| time_zone_name            |</span><br><span class="line">| time_zone_transition      |</span><br><span class="line">| time_zone_transition_type |</span><br><span class="line">| user                      |</span><br><span class="line">+---------------------------+</span><br><span class="line">31 rows <span class="keyword">in</span> <span class="built_in">set</span> (0.00 sec)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 8. 退出</span></span><br><span class="line">mysql&gt;<span class="built_in">exit</span>;</span><br></pre></td></tr></table></figure>





<h3 id="2-2-Python代码操作"><a href="#2-2-Python代码操作" class="headerlink" title="2.2 Python代码操作"></a>2.2 Python代码操作</h3><p>无论通过何种方式去连接MySQL，本质上发送的 <strong>指令</strong> 都是相同的，只是连接的方式和操作形式不同而已。</p>
<p>当连接上MySQL之后，执行如下指令，就可以对MySQL的数据进行操作。（同上述过程）</p>
<ul>
<li>查看当前所有的数据库  <code>show databases;</code></li>
<li>创建数据库：<code>create database 数据库名 default charset utf8 collate utf8_general_ci;</code> </li>
<li>删除数据库：<code>drop database 数据库名</code>;</li>
<li>进入数据（进入文件）：<code>use 数据库;</code></li>
</ul>
<p>想要使用Python操作MySQL需要安装第三方模块：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3 install pymysql</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510153336093.png" alt="image-20210510153336093"></p>
<p>安装完成后，就可以编写代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"></span><br><span class="line"><span class="comment"># 连接MySQL（socket）</span></span><br><span class="line">conn = pymysql.connect(host=<span class="string">&#x27;127.0.0.1&#x27;</span>, port=<span class="number">3306</span>, user=<span class="string">&#x27;root&#x27;</span>, passwd=<span class="string">&#x27;root123&#x27;</span>, charset=<span class="string">&quot;utf8&quot;</span>)</span><br><span class="line">cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 1. 查看数据库</span></span><br><span class="line"><span class="comment"># 发送指令</span></span><br><span class="line">cursor.execute(<span class="string">&quot;show databases&quot;</span>)</span><br><span class="line"><span class="comment"># 获取指令的结果</span></span><br><span class="line">result = cursor.fetchall()</span><br><span class="line"><span class="built_in">print</span>(result) <span class="comment"># ((&#x27;information_schema&#x27;,), (&#x27;mysql&#x27;,), (&#x27;performance_schema&#x27;,), (&#x27;sys&#x27;,))</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 2. 创建数据库（新增、删除、修改）</span></span><br><span class="line"><span class="comment"># 发送指令</span></span><br><span class="line">cursor.execute(<span class="string">&quot;create database db3 default charset utf8 collate utf8_general_ci&quot;</span>)</span><br><span class="line">conn.commit()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 查看数据库</span></span><br><span class="line"><span class="comment"># 发送指令</span></span><br><span class="line">cursor.execute(<span class="string">&quot;show databases&quot;</span>)</span><br><span class="line"><span class="comment"># 获取指令的结果</span></span><br><span class="line">result = cursor.fetchall()</span><br><span class="line"><span class="built_in">print</span>(result) <span class="comment"># ((&#x27;information_schema&#x27;,), (&#x27;db3&#x27;,), (&#x27;mysql&#x27;,), (&#x27;performance_schema&#x27;,), (&#x27;sys&#x27;,))</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 4. 删除数据库</span></span><br><span class="line"><span class="comment"># 发送指令</span></span><br><span class="line">cursor.execute(<span class="string">&quot;drop database db3&quot;</span>)</span><br><span class="line">conn.commit()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 3. 查看数据库</span></span><br><span class="line"><span class="comment"># 发送指令</span></span><br><span class="line">cursor.execute(<span class="string">&quot;show databases&quot;</span>)</span><br><span class="line"><span class="comment"># 获取指令的结果</span></span><br><span class="line">result = cursor.fetchall()</span><br><span class="line"><span class="built_in">print</span>(result) <span class="comment"># ((&#x27;information_schema&#x27;,), (&#x27;mysql&#x27;,), (&#x27;performance_schema&#x27;,), (&#x27;sys&#x27;,))</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 5. 进入数据库，查看表</span></span><br><span class="line"><span class="comment"># 发送指令</span></span><br><span class="line">cursor.execute(<span class="string">&quot;use mysql&quot;</span>)</span><br><span class="line">cursor.execute(<span class="string">&quot;show tables&quot;</span>)</span><br><span class="line">result = cursor.fetchall()</span><br><span class="line"><span class="built_in">print</span>(result) <span class="comment"># ((&#x27;columns_priv&#x27;,), (&#x27;db&#x27;,), (&#x27;engine_cost&#x27;,), (&#x27;event&#x27;,), (&#x27;func&#x27;,), (&#x27;general_log&#x27;,),....</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 关闭连接</span></span><br><span class="line">cursor.close()</span><br><span class="line">conn.close()</span><br></pre></td></tr></table></figure>



<h2 id="3-数据表-管理"><a href="#3-数据表-管理" class="headerlink" title="3. 数据表 管理"></a>3. 数据表 管理</h2><p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210507211911641.png" alt="image-20210507211911641"></p>
<p>如果将数据库管理系统与之前的文件管理做类比的话：</p>
<table>
<thead>
<tr>
<th>数据库管理系统</th>
<th>文件管理</th>
</tr>
</thead>
<tbody><tr>
<td>数据库</td>
<td>文件夹</td>
</tr>
<tr>
<td>数据表</td>
<td>文件夹下的文件</td>
</tr>
</tbody></table>
<p>接下来，我们先学习 数据表（文件夹中的文件）相关操作的指令。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210510153336093.png" alt="image-20210510153336093"></p>
<p>其实在数据库中创建数据库 和 创建Excel非常类似，需要指定： <code>表名</code>、<code>列名称</code>、<code>类类型（整型、字符串或其他)</code>。</p>
<h3 id="3-1-内置客户端操作"><a href="#3-1-内置客户端操作" class="headerlink" title="3.1 内置客户端操作"></a>3.1 内置客户端操作</h3><p>数据表常见操作的指令：</p>
<ul>
<li><p>进入数据库 <code>use 数据库;</code>，查看当前所有表：<code>show tables;</code></p>
</li>
<li><p>创建表结构<br><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210511102323966.png" alt="image-20210511102323966"></p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> 表名(</span><br><span class="line">    列名  类型,</span><br><span class="line">    列名  类型,</span><br><span class="line">    列名  类型</span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tb1(</span><br><span class="line">	id <span class="type">int</span>,</span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">16</span>)</span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tb2(</span><br><span class="line">	id <span class="type">int</span>,</span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">16</span>) <span class="keyword">not</span> <span class="keyword">null</span>,   <span class="comment">-- 不允许为空</span></span><br><span class="line">    email <span class="type">varchar</span>(<span class="number">32</span>) <span class="keyword">null</span>,      <span class="comment">-- 允许为空（默认）</span></span><br><span class="line">    age <span class="type">int</span></span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tb3(</span><br><span class="line">	id <span class="type">int</span>,</span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">16</span>) <span class="keyword">not</span> <span class="keyword">null</span>,   <span class="comment">-- 不允许为空</span></span><br><span class="line">    email <span class="type">varchar</span>(<span class="number">32</span>) <span class="keyword">null</span>,      <span class="comment">-- 允许为空（默认）</span></span><br><span class="line">    age <span class="type">int</span> <span class="keyword">default</span> <span class="number">3</span>            <span class="comment">-- 插入数据时，如果不给age列设置值，默认值：3</span></span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tb4(</span><br><span class="line">	id <span class="type">int</span> <span class="keyword">primary</span> key,			 <span class="comment">-- 主键（不允许为空、不能重复）</span></span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">16</span>) <span class="keyword">not</span> <span class="keyword">null</span>,   <span class="comment">-- 不允许为空</span></span><br><span class="line">    email <span class="type">varchar</span>(<span class="number">32</span>) <span class="keyword">null</span>,      <span class="comment">-- 允许为空（默认）</span></span><br><span class="line">    age <span class="type">int</span> <span class="keyword">default</span> <span class="number">3</span>            <span class="comment">-- 插入数据时，如果不给age列设置值，默认值：3</span></span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<p>主键一般用于表示当前这条数据的ID编号（类似于人的身份证），需要我们自己来维护一个不重复的值，比较繁琐。所以，在数据库中一般会将主键和自增结合。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> tb5(</span><br><span class="line">	id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> auto_increment <span class="keyword">primary</span> key,	<span class="comment">-- 不允许为空 &amp; 主键 &amp; 自增</span></span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">16</span>) <span class="keyword">not</span> <span class="keyword">null</span>,   		<span class="comment">-- 不允许为空</span></span><br><span class="line">    email <span class="type">varchar</span>(<span class="number">32</span>) <span class="keyword">null</span>,      		<span class="comment">-- 允许为空（默认）</span></span><br><span class="line">    age <span class="type">int</span> <span class="keyword">default</span> <span class="number">3</span>            		<span class="comment">-- 插入数据时，如果不给age列设置值，默认值：3</span></span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<p>注意：一个表中只能有一个自增列【自增列，一般都是主键】。</p>
</li>
<li><p>删除表 <code>drop table 表名;</code></p>
</li>
<li><p>清空表 <code>delete from 表名;</code> 或 <code>truncate table 表名;</code>（速度快、无法回滚撤销等）</p>
</li>
<li><p>修改表</p>
<ul>
<li><p>添加列 </p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">add</span> 列名 类型;</span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">add</span> 列名 类型 <span class="keyword">DEFAULT</span> 默认值;</span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">add</span> 列名 类型 <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">default</span> 默认值;</span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">add</span> 列名 类型 <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment;</span><br></pre></td></tr></table></figure></li>
<li><p>删除列</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">drop</span> <span class="keyword">column</span> 列名;</span><br></pre></td></tr></table></figure></li>
<li><p>修改列 类型</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 modify <span class="keyword">column</span> 列名 类型;</span><br></pre></td></tr></table></figure></li>
<li><p>修改列 类型 + 名称</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 change 原列名 新列名 新类型;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span>  tb change id nid <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span>;</span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span>  tb change id id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">default</span> <span class="number">5</span>;</span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span>  tb change id id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment;</span><br><span class="line"></span><br><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span>  tb change id id <span class="type">int</span>; <span class="comment">-- 允许为空，删除默认值，删除自增。</span></span><br></pre></td></tr></table></figure></li>
<li><p>修改列 默认值</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> 表名 <span class="keyword">ALTER</span> 列名 <span class="keyword">SET</span> <span class="keyword">DEFAULT</span> <span class="number">1000</span>;</span><br></pre></td></tr></table></figure></li>
<li><p>删除列 默认值</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> 表名 <span class="keyword">ALTER</span> 列名 <span class="keyword">DROP</span> <span class="keyword">DEFAULT</span>;</span><br></pre></td></tr></table></figure></li>
<li><p>添加主键</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">add</span> <span class="keyword">primary</span> key(列名);</span><br></pre></td></tr></table></figure></li>
<li><p>删除主键</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">alter</span> <span class="keyword">table</span> 表名 <span class="keyword">drop</span> <span class="keyword">primary</span> key;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>常见列类型</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> 表(</span><br><span class="line">	id <span class="type">int</span>,</span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">16</span>)</span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>

<ul>
<li><p><code>int[(m)][unsigned][zerofill]</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">int				表示有符号，取值范围：-2147483648 ～ 2147483647</span><br><span class="line">int unsigned	表示无符号，取值范围：0 ～ 4294967295</span><br><span class="line">int(5)zerofill	仅用于显示，当不满足5位时，按照左边补0，例如：00002；满足时，正常显示。</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">create</span> <span class="keyword">table</span> L1(id <span class="type">int</span>, uid <span class="type">int</span> unsigned, zid <span class="type">int</span>(<span class="number">5</span>) zerofill) <span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br><span class="line">Query OK, <span class="number">0</span> <span class="keyword">rows</span> affected (<span class="number">0.03</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L1(id,uid,zid) <span class="keyword">values</span>(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L1(id,uid,zid) <span class="keyword">values</span>(<span class="number">2147483641</span>,<span class="number">4294967294</span>,<span class="number">300000</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> L1;</span><br><span class="line"><span class="operator">+</span><span class="comment">------------+------------+--------+</span></span><br><span class="line"><span class="operator">|</span> id         <span class="operator">|</span> uid        <span class="operator">|</span> zid    <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">------------+------------+--------+</span></span><br><span class="line"><span class="operator">|</span>          <span class="number">1</span> <span class="operator">|</span>          <span class="number">2</span> <span class="operator">|</span>  <span class="number">00003</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span> <span class="number">2147483641</span> <span class="operator">|</span> <span class="number">4294967294</span> <span class="operator">|</span> <span class="number">300000</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">------------+------------+--------+</span></span><br><span class="line"><span class="number">2</span> <span class="keyword">rows</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L1(id,uid,zid) <span class="keyword">values</span>(<span class="number">214748364100</span>,<span class="number">4294967294</span>,<span class="number">300000</span>);</span><br><span class="line">ERROR <span class="number">1264</span> (<span class="number">22003</span>): <span class="keyword">Out</span> <span class="keyword">of</span> <span class="keyword">range</span> <span class="keyword">value</span> <span class="keyword">for</span> <span class="keyword">column</span> <span class="string">&#x27;id&#x27;</span> <span class="keyword">at</span> <span class="type">row</span> <span class="number">1</span></span><br><span class="line">mysql<span class="operator">&gt;</span></span><br></pre></td></tr></table></figure></li>
<li><p><code>tinyint[(m)] [unsigned] [zerofill]</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">有符号，取值范围：-128 ～ 127.</span><br><span class="line">无符号，取值范围：0 ～ 255</span><br></pre></td></tr></table></figure></li>
<li><p><code>bigint[(m)][unsigned][zerofill]</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">有符号，取值范围：-9223372036854775808 ～ 9223372036854775807</span><br><span class="line">无符号，取值范围：0  ～  18446744073709551615</span><br></pre></td></tr></table></figure></li>
<li><p><code>decimal[(m[,d])] [unsigned] [zerofill]</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">准确的小数值，m是数字总个数（负号不算），d是小数点后个数。 m最大值为65，d最大值为30。</span><br><span class="line"></span><br><span class="line">例如：</span><br><span class="line">create table L2(</span><br><span class="line">	id int not null primary key auto_increment,</span><br><span class="line">	salary decimal(8,2)</span><br><span class="line">)default charset=utf8;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">create</span> <span class="keyword">table</span> L2(id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment,salary <span class="type">decimal</span>(<span class="number">8</span>,<span class="number">2</span>))<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br><span class="line">Query OK, <span class="number">0</span> <span class="keyword">rows</span> affected (<span class="number">0.03</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L2(salary) <span class="keyword">values</span>(<span class="number">1.28</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected (<span class="number">0.01</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L2(salary) <span class="keyword">values</span>(<span class="number">5.289</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected, <span class="number">1</span> warning (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L2(salary) <span class="keyword">values</span>(<span class="number">5.282</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected, <span class="number">1</span> warning (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L2(salary) <span class="keyword">values</span>(<span class="number">512132.28</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L2(salary) <span class="keyword">values</span>(<span class="number">512132.283</span>);</span><br><span class="line">Query OK, <span class="number">1</span> <span class="type">row</span> affected, <span class="number">1</span> warning (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> L2;</span><br><span class="line"><span class="operator">+</span><span class="comment">----+-----------+</span></span><br><span class="line"><span class="operator">|</span> id <span class="operator">|</span> salary    <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+-----------+</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">1</span> <span class="operator">|</span>      <span class="number">1.28</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">2</span> <span class="operator">|</span>      <span class="number">5.29</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">3</span> <span class="operator">|</span>      <span class="number">5.28</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">4</span> <span class="operator">|</span> <span class="number">512132.28</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">5</span> <span class="operator">|</span> <span class="number">512132.28</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+-----------+</span></span><br><span class="line"><span class="number">5</span> <span class="keyword">rows</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L2(salary) <span class="keyword">values</span>(<span class="number">5121321.283</span>);</span><br><span class="line">ERROR <span class="number">1264</span> (<span class="number">22003</span>): <span class="keyword">Out</span> <span class="keyword">of</span> <span class="keyword">range</span> <span class="keyword">value</span> <span class="keyword">for</span> <span class="keyword">column</span> <span class="string">&#x27;salary&#x27;</span> <span class="keyword">at</span> <span class="type">row</span> <span class="number">1</span></span><br><span class="line">mysql<span class="operator">&gt;</span></span><br></pre></td></tr></table></figure></li>
<li><p><code>FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">单精度浮点数，非准确小数值，m是数字总个数，d是小数点后个数。</span><br></pre></td></tr></table></figure></li>
<li><p><code>DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">双精度浮点数（非准确小数值），m是数字总个数，d是小数点后个数。</span><br></pre></td></tr></table></figure></li>
<li><p><code>char(m)</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">定长字符串，m代表字符串的长度，最多可容纳255个字符。</span><br><span class="line"></span><br><span class="line">定长的体现：即使内容长度小于m，也会占用m长度。例如：char(5)，数据是：yes，底层也会占用5个字符；如果超出m长度限制（默认MySQL是严格模式，所以会报错）。</span><br><span class="line">    如果在配置文件中加入如下配置，</span><br><span class="line">        sql-mode=&quot;NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION&quot;</span><br><span class="line">    保存并重启，此时MySQL则是非严格模式，此时超过长度则自动截断（不报错）。。</span><br><span class="line"></span><br><span class="line">注意：默认底层存储是固定的长度（不够则用空格补齐），但是查询数据时，会自动将空白去除。 如果想要保留空白，在sql-mode中加入 PAD_CHAR_TO_FULL_LENGTH 即可。</span><br><span class="line">查看模式sql-mode，执行命令：show variables  like &#x27;sql_mode&#x27;;</span><br><span class="line"></span><br><span class="line">一般适用于：固定长度的内容。</span><br><span class="line"></span><br><span class="line">create table L3(</span><br><span class="line">    id int not null primary key auto_increment,</span><br><span class="line">    name varchar(5),</span><br><span class="line">    depart char(3)</span><br><span class="line">)default charset=utf8;</span><br><span class="line"></span><br><span class="line">insert into L3(name,depart) values(&quot;alexsb&quot;,&quot;sbalex&quot;);</span><br></pre></td></tr></table></figure></li>
<li><p><code>varchar(m)</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">变长字符串，m代表字符串的长度，最多可容纳65535个字节。</span><br><span class="line"></span><br><span class="line">变长的体现：内容小于m时，会按照真实数据长度存储；如果超出m长度限制（（默认MySQL是严格模式，所以会报错）。</span><br><span class="line">    如果在配置文件中加入如下配置，</span><br><span class="line">        sql-mode=&quot;NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION&quot;</span><br><span class="line">    保存并重启，此时MySQL则是非严格模式，此时超过长度则自动截断（不报错）。</span><br><span class="line"></span><br><span class="line">例如：</span><br><span class="line">create table L3(</span><br><span class="line">    id int not null primary key auto_increment,</span><br><span class="line">    name varchar(5),</span><br><span class="line">    depart char(3)</span><br><span class="line">)default charset=utf8;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">create</span> <span class="keyword">table</span> L3(id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment,name <span class="type">varchar</span>(<span class="number">5</span>),depart <span class="type">char</span>(<span class="number">3</span>))<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br><span class="line">Query OK, <span class="number">0</span> <span class="keyword">rows</span> affected (<span class="number">0.03</span> sec)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 插入多行</span></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L3(name,depart) <span class="keyword">values</span>(&quot;wu&quot;,&quot;WU&quot;),(&quot;wupei&quot;,&quot;ALS&quot;);</span><br><span class="line">Query OK, <span class="number">2</span> <span class="keyword">rows</span> affected (<span class="number">0.00</span> sec)</span><br><span class="line">Records: <span class="number">2</span>  Duplicates: <span class="number">0</span>  Warnings: <span class="number">0</span></span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> L3;</span><br><span class="line"><span class="operator">+</span><span class="comment">----+-------+--------+</span></span><br><span class="line"><span class="operator">|</span> id <span class="operator">|</span> name  <span class="operator">|</span> depart <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+-------+--------+</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">1</span> <span class="operator">|</span> wu    <span class="operator">|</span> WU     <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">2</span> <span class="operator">|</span> wupei <span class="operator">|</span> ALS    <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+-------+--------+</span></span><br><span class="line"><span class="number">2</span> <span class="keyword">rows</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 非严格模式下，不会报错。</span></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L3(name,depart) <span class="keyword">values</span>(&quot;wupeiqi&quot;,&quot;ALS&quot;);</span><br><span class="line">ERROR <span class="number">1406</span> (<span class="number">22001</span>): Data too long <span class="keyword">for</span> <span class="keyword">column</span> <span class="string">&#x27;name&#x27;</span> <span class="keyword">at</span> <span class="type">row</span> <span class="number">1</span></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L3(name,depart) <span class="keyword">values</span>(&quot;wupei&quot;,&quot;ALSB&quot;);</span><br><span class="line">ERROR <span class="number">1406</span> (<span class="number">22001</span>): Data too long <span class="keyword">for</span> <span class="keyword">column</span> <span class="string">&#x27;depart&#x27;</span> <span class="keyword">at</span> <span class="type">row</span> <span class="number">1</span></span><br><span class="line">mysql<span class="operator">&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 如果 sql-mode 中加入了 PAD_CHAR_TO_FULL_LENGTH ，则查询时char时空白会保留。</span></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> name,length(name),depart,length(depart) <span class="keyword">from</span> L3;</span><br><span class="line"><span class="operator">+</span><span class="comment">-------+--------------+--------+----------------+</span></span><br><span class="line"><span class="operator">|</span> name  <span class="operator">|</span> length(name) <span class="operator">|</span> depart <span class="operator">|</span> length(depart) <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">-------+--------------+--------+----------------+</span></span><br><span class="line"><span class="operator">|</span> wu    <span class="operator">|</span>            <span class="number">2</span> <span class="operator">|</span> WU     <span class="operator">|</span>              <span class="number">3</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span> wupei <span class="operator">|</span>            <span class="number">5</span> <span class="operator">|</span> ALS    <span class="operator">|</span>              <span class="number">3</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">-------+--------------+--------+----------------+</span></span><br><span class="line"><span class="number">4</span> <span class="keyword">rows</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br><span class="line">mysql<span class="operator">&gt;</span></span><br></pre></td></tr></table></figure></li>
<li><p><code>text</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">text数据类型用于保存变长的大字符串，可以组多到65535 (2**16 − 1)个字符。</span><br><span class="line"></span><br><span class="line">一般情况下，长文本会用text类型。例如：文章、新闻等。</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> L4(</span><br><span class="line">	id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment,</span><br><span class="line">    title <span class="type">varchar</span>(<span class="number">128</span>),</span><br><span class="line">	content text</span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure></li>
<li><p><code>mediumtext</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters.</span><br></pre></td></tr></table></figure></li>
<li><p><code>longtext</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1)</span><br></pre></td></tr></table></figure></li>
<li><p><code>datetime</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">YYYY-MM-DD HH:MM:SS（1000-01-01 00:00:00/9999-12-31 23:59:59）</span><br></pre></td></tr></table></figure></li>
<li><p><code>timestamp</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">YYYY-MM-DD HH:MM:SS（1970-01-01 00:00:00/2037年）</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">对于TIMESTAMP，它把客户端插入的时间从当前时区转化为UTC（世界标准时间）进行存储，查询时，将其又转化为客户端当前时区进行返回。</span><br><span class="line"></span><br><span class="line">对于DATETIME，不做任何改变，原样输入和输出。</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">create</span> <span class="keyword">table</span> L5(</span><br><span class="line">    <span class="operator">-</span><span class="operator">&gt;</span> id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment,</span><br><span class="line">    <span class="operator">-</span><span class="operator">&gt;</span> dt datetime,</span><br><span class="line">    <span class="operator">-</span><span class="operator">&gt;</span> tt <span class="type">timestamp</span></span><br><span class="line">    <span class="operator">-</span><span class="operator">&gt;</span> )<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br><span class="line">Query OK, <span class="number">0</span> <span class="keyword">rows</span> affected (<span class="number">0.03</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">insert</span> <span class="keyword">into</span> L5(dt,tt) <span class="keyword">values</span>(&quot;2025-11-11 11:11:44&quot;, &quot;2025-11-11 11:11:44&quot;);</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> L5;</span><br><span class="line"><span class="operator">+</span><span class="comment">----+---------------------+---------------------+</span></span><br><span class="line"><span class="operator">|</span> id <span class="operator">|</span> dt                  <span class="operator">|</span> tt                  <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+---------------------+---------------------+</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">1</span> <span class="operator">|</span> <span class="number">2025</span><span class="number">-11</span><span class="number">-11</span> <span class="number">11</span>:<span class="number">11</span>:<span class="number">44</span> <span class="operator">|</span> <span class="number">2025</span><span class="number">-11</span><span class="number">-11</span> <span class="number">11</span>:<span class="number">11</span>:<span class="number">44</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+---------------------+---------------------+</span></span><br><span class="line"><span class="number">1</span> <span class="type">row</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> variables <span class="keyword">like</span> <span class="string">&#x27;%time_zone%&#x27;</span>;</span><br><span class="line"><span class="operator">+</span><span class="comment">------------------+--------+</span></span><br><span class="line"><span class="operator">|</span> Variable_name    <span class="operator">|</span> <span class="keyword">Value</span>  <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">------------------+--------+</span></span><br><span class="line"><span class="operator">|</span> system_time_zone <span class="operator">|</span> CST    <span class="operator">|</span> </span><br><span class="line"><span class="operator">|</span> time_zone        <span class="operator">|</span> <span class="keyword">SYSTEM</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">------------------+--------+</span></span><br><span class="line"><span class="number">2</span> <span class="keyword">rows</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br><span class="line"><span class="comment">-- “CST”指的是MySQL所在主机的系统时间，是中国标准时间的缩写，China Standard Time UT+8:00</span></span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">set</span> time_zone<span class="operator">=</span><span class="string">&#x27;+0:00&#x27;</span>;</span><br><span class="line">Query OK, <span class="number">0</span> <span class="keyword">rows</span> affected (<span class="number">0.00</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">show</span> variables <span class="keyword">like</span> <span class="string">&#x27;%time_zone%&#x27;</span>;</span><br><span class="line"><span class="operator">+</span><span class="comment">------------------+--------+</span></span><br><span class="line"><span class="operator">|</span> Variable_name    <span class="operator">|</span> <span class="keyword">Value</span>  <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">------------------+--------+</span></span><br><span class="line"><span class="operator">|</span> system_time_zone <span class="operator">|</span> CST    <span class="operator">|</span></span><br><span class="line"><span class="operator">|</span> time_zone        <span class="operator">|</span> <span class="operator">+</span><span class="number">00</span>:<span class="number">00</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">------------------+--------+</span></span><br><span class="line"><span class="number">2</span> <span class="keyword">rows</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.01</span> sec)</span><br><span class="line"></span><br><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> L5;</span><br><span class="line"><span class="operator">+</span><span class="comment">----+---------------------+---------------------+</span></span><br><span class="line"><span class="operator">|</span> id <span class="operator">|</span> dt                  <span class="operator">|</span> tt                  <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+---------------------+---------------------+</span></span><br><span class="line"><span class="operator">|</span>  <span class="number">1</span> <span class="operator">|</span> <span class="number">2025</span><span class="number">-11</span><span class="number">-11</span> <span class="number">11</span>:<span class="number">11</span>:<span class="number">44</span> <span class="operator">|</span> <span class="number">2025</span><span class="number">-11</span><span class="number">-11</span> <span class="number">03</span>:<span class="number">11</span>:<span class="number">44</span> <span class="operator">|</span></span><br><span class="line"><span class="operator">+</span><span class="comment">----+---------------------+---------------------+</span></span><br><span class="line"><span class="number">1</span> <span class="type">row</span> <span class="keyword">in</span> <span class="keyword">set</span> (<span class="number">0.00</span> sec)</span><br></pre></td></tr></table></figure></li>
<li><p><code>date</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">YYYY-MM-DD（1000-01-01/9999-12-31）</span><br></pre></td></tr></table></figure></li>
<li><p><code>time</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HH:MM:SS（&#x27;-838:59:59&#x27;/&#x27;838:59:59&#x27;）</span><br></pre></td></tr></table></figure></li>
</ul>
<p>MySQL还有很多其他的数据类型，例如：<em>set、enum、TinyBlob、Blob、MediumBlob、LongBlob 等</em>，详细见官方文档：<a target="_blank" rel="noopener" href="https://dev.mysql.com/doc/refman/5.7/en/data-types.html">https://dev.mysql.com/doc/refman/5.7/en/data-types.html</a></p>
</li>
</ul>
<p>上述就是关于数据表的一些基本操作。</p>
<h3 id="3-2-MySQL代码操作"><a href="#3-2-MySQL代码操作" class="headerlink" title="3.2 MySQL代码操作"></a>3.2 MySQL代码操作</h3><p>基于Python去连接MySQL之后，想要进行数据表的管理的话，发送的指令其实都是相同的，例如：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">import pymysql</span><br><span class="line"></span><br><span class="line"># 连接MySQL</span><br><span class="line">conn <span class="operator">=</span> pymysql.connect(host<span class="operator">=</span><span class="string">&#x27;127.0.0.1&#x27;</span>, port<span class="operator">=</span><span class="number">3306</span>, <span class="keyword">user</span><span class="operator">=</span><span class="string">&#x27;root&#x27;</span>, passwd<span class="operator">=</span><span class="string">&#x27;root123&#x27;</span>, charset<span class="operator">=</span>&quot;utf8&quot;)</span><br><span class="line"><span class="keyword">cursor</span> <span class="operator">=</span> conn.cursor()</span><br><span class="line"></span><br><span class="line"># <span class="number">1.</span> 创建数据库</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">cursor.execute(&quot;<span class="keyword">create</span> database db4 <span class="keyword">default</span> charset utf8 <span class="keyword">collate</span> utf8_general_ci&quot;)</span><br><span class="line">conn.commit()</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line"></span><br><span class="line"># <span class="number">2.</span> 进入数据库、查看数据表</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">cursor.execute(&quot;use db4&quot;)</span><br><span class="line">cursor.execute(&quot;<span class="keyword">show</span> tables&quot;)</span><br><span class="line">result = cursor.fetchall()</span><br><span class="line">print(result)</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line"></span><br><span class="line"># <span class="number">3.</span> 进入数据库创建表</span><br><span class="line">cursor.execute(&quot;use db4&quot;)</span><br><span class="line"><span class="keyword">sql</span> <span class="operator">=</span> &quot;&quot;&quot;</span><br><span class="line">create table L4(</span><br><span class="line">    id int not null primary key auto_increment,</span><br><span class="line">    title varchar(128),</span><br><span class="line">    content text,</span><br><span class="line">    ctime datetime</span><br><span class="line">)default charset=utf8;</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">cursor.execute(<span class="keyword">sql</span>)</span><br><span class="line">conn.commit()</span><br><span class="line"></span><br><span class="line"># <span class="number">4.</span> 查看数据库中的表</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line">cursor.execute(&quot;<span class="keyword">show</span> tables&quot;)</span><br><span class="line">result = cursor.fetchall()</span><br><span class="line">print(result)</span><br><span class="line">&quot;&quot;&quot;</span><br><span class="line"></span><br><span class="line"># <span class="number">5.</span> 其他 <span class="keyword">drop</span> table... 略过</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 关闭连接</span><br><span class="line">cursor.close()</span><br><span class="line">conn.close()</span><br></pre></td></tr></table></figure>







<h2 id="4-数据行"><a href="#4-数据行" class="headerlink" title="4.数据行"></a>4.数据行</h2><p>当数据库和数据表创建完成之后，就需要对数据表中的内容进行：增、删、改、查了。</p>
<p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210511102323966.png" alt="image-20210511102323966"></p>
<h3 id="4-1-内置客户端操作"><a href="#4-1-内置客户端操作" class="headerlink" title="4.1 内置客户端操作"></a>4.1 内置客户端操作</h3><p>数据行操作的相关SQL语句（指令）如下：</p>
<ul>
<li><p>新<strong>增</strong>数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">insert into 表名 (列名,列名,列名) values(对应列的值,对应列的值,对应列的值);</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> tb1(name,password) <span class="keyword">values</span>(<span class="string">&#x27;武沛齐&#x27;</span>,<span class="string">&#x27;123123&#x27;</span>);</span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> tb1(name,password) <span class="keyword">values</span>(<span class="string">&#x27;武沛齐&#x27;</span>,<span class="string">&#x27;123123&#x27;</span>),(<span class="string">&#x27;alex&#x27;</span>,<span class="string">&#x27;123&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">insert</span> <span class="keyword">into</span> tb1 <span class="keyword">values</span>(<span class="string">&#x27;武沛齐&#x27;</span>,<span class="string">&#x27;123123&#x27;</span>),(<span class="string">&#x27;alex&#x27;</span>,<span class="string">&#x27;123&#x27;</span>); <span class="comment">-- 如果表中只有2列</span></span><br></pre></td></tr></table></figure></li>
<li><p><strong>删</strong>除数据</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> 表名;</span><br><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> 表名 <span class="keyword">where</span> 条件;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> tb1;</span><br><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> name<span class="operator">=</span>&quot;wupeiqi&quot;;</span><br><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> name<span class="operator">=</span>&quot;wupeiqi&quot; <span class="keyword">and</span> password<span class="operator">=</span>&quot;123&quot;;</span><br><span class="line"><span class="keyword">delete</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> id<span class="operator">&gt;</span><span class="number">9</span>;</span><br></pre></td></tr></table></figure></li>
<li><p>修<strong>改</strong>数据</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">update 表名 <span class="keyword">set</span> 列名<span class="operator">=</span>值;</span><br><span class="line">update 表名 <span class="keyword">set</span> 列名<span class="operator">=</span>值 <span class="keyword">where</span> 条件;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">update tb1 <span class="keyword">set</span> name<span class="operator">=</span>&quot;wupeiqi&quot;;</span><br><span class="line">update tb1 <span class="keyword">set</span> name<span class="operator">=</span>&quot;wupeiqi&quot; <span class="keyword">where</span> id<span class="operator">=</span><span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">update tb1 <span class="keyword">set</span> age<span class="operator">=</span>age<span class="operator">+</span><span class="number">1</span>;  <span class="comment">-- 整型</span></span><br><span class="line">update tb1 <span class="keyword">set</span> age<span class="operator">=</span>age<span class="operator">+</span><span class="number">1</span> <span class="keyword">where</span> id<span class="operator">=</span><span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">update L3 <span class="keyword">set</span> name<span class="operator">=</span>concat(name,&quot;db&quot;);</span><br><span class="line">update L3 <span class="keyword">set</span> name<span class="operator">=</span>concat(name,&quot;123&quot;)  <span class="keyword">where</span> id<span class="operator">=</span><span class="number">2</span>;  <span class="comment">-- concat一个函数，可以拼接字符串</span></span><br></pre></td></tr></table></figure></li>
<li><p><strong>查</strong>询数据</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> 表名;</span><br><span class="line"><span class="keyword">select</span> 列名,列名,列名 <span class="keyword">from</span> 表名;</span><br><span class="line"><span class="keyword">select</span> 列名,列名 <span class="keyword">as</span> 别名,列名 <span class="keyword">from</span> 表名;</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> 表名 <span class="keyword">where</span> 条件;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> tb1;</span><br><span class="line"><span class="keyword">select</span> id,name,age <span class="keyword">from</span> tb1;</span><br><span class="line"><span class="keyword">select</span> id,name <span class="keyword">as</span> N,age, <span class="keyword">from</span> tb1;</span><br><span class="line"><span class="keyword">select</span> id,name <span class="keyword">as</span> N,age, <span class="number">111</span> <span class="keyword">from</span> tb1;</span><br><span class="line"></span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> id <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> id <span class="operator">&gt;</span> <span class="number">1</span>;</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> id <span class="operator">!=</span> <span class="number">1</span>;</span><br><span class="line"><span class="keyword">select</span> <span class="operator">*</span> <span class="keyword">from</span> tb1 <span class="keyword">where</span> name<span class="operator">=</span>&quot;wupeiqi&quot; <span class="keyword">and</span> password<span class="operator">=</span>&quot;123&quot;;</span><br></pre></td></tr></table></figure></li>
</ul>
<h3 id="4-2-Python代码操作"><a href="#4-2-Python代码操作" class="headerlink" title="4.2 Python代码操作"></a>4.2 Python代码操作</h3><p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210511102323966.png" alt="image-20210511102323966"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"></span><br><span class="line"><span class="comment"># 连接MySQL，自动执行 use userdb; -- 进入数据库</span></span><br><span class="line">conn = pymysql.connect(host=<span class="string">&#x27;127.0.0.1&#x27;</span>, port=<span class="number">3306</span>, user=<span class="string">&#x27;root&#x27;</span>, passwd=<span class="string">&#x27;root123&#x27;</span>, charset=<span class="string">&quot;utf8&quot;</span>, db=<span class="string">&#x27;userdb&#x27;</span>)</span><br><span class="line">cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 1.新增（需commit）</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">cursor.execute(&quot;insert into tb1(name,password) values(&#x27;武沛齐&#x27;,&#x27;123123&#x27;)&quot;)</span></span><br><span class="line"><span class="string">conn.commit()</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 2.删除（需commit）</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">cursor.execute(&quot;delete from tb1 where id=1&quot;)</span></span><br><span class="line"><span class="string">conn.commit()</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 3.修改（需commit)</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">cursor.execute(&quot;update tb1 set name=&#x27;xx&#x27; where id=1&quot;)</span></span><br><span class="line"><span class="string">conn.commit()</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 4.查询</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">cursor.execute(&quot;select * from tb where id&gt;10&quot;)</span></span><br><span class="line"><span class="string">data = cursor.fetchone() # cursor.fetchall()</span></span><br><span class="line"><span class="string">print(data)</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 关闭连接</span></span><br><span class="line">cursor.close()</span><br><span class="line">conn.close()</span><br></pre></td></tr></table></figure>





<p>其实在真正做项目开发时，流程如下：</p>
<ul>
<li>第一步：根据项目的功能来设计相应的 数据库 &amp; 表结构（不会经常变动，在项目设计之初就确定好了）。</li>
<li>第二步：操作表结构中的数据，已达到实现业务逻辑的目的。</li>
</ul>
<p><strong>例如：实现一个 用户管理系统。</strong></p>
<p>先使用MySQL自带的客户端创建相关 数据库和表结构（相当于先创建好Excel结构）。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> database usersdb <span class="keyword">default</span> charset utf8 <span class="keyword">collate</span> utf8_general_ci;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> users(</span><br><span class="line">	id <span class="type">int</span> <span class="keyword">not</span> <span class="keyword">null</span> <span class="keyword">primary</span> key auto_increment,</span><br><span class="line">    name <span class="type">varchar</span>(<span class="number">32</span>),</span><br><span class="line">	password <span class="type">varchar</span>(<span class="number">64</span>)</span><br><span class="line">)<span class="keyword">default</span> charset<span class="operator">=</span>utf8;</span><br></pre></td></tr></table></figure>



<p>再在程序中执行编写相应的功能实现 注册、登录 等功能。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">register</span>():</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;用户注册&quot;</span>)</span><br><span class="line"></span><br><span class="line">    user = <span class="built_in">input</span>(<span class="string">&quot;请输入用户名：&quot;</span>) <span class="comment"># alex</span></span><br><span class="line">    password = <span class="built_in">input</span>(<span class="string">&quot;请输入密码：&quot;</span>) <span class="comment"># sb</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># 连接指定数据</span></span><br><span class="line">    conn = pymysql.connect(host=<span class="string">&#x27;127.0.0.1&#x27;</span>, port=<span class="number">3306</span>, user=<span class="string">&#x27;root&#x27;</span>, passwd=<span class="string">&#x27;root123&#x27;</span>, charset=<span class="string">&quot;utf8&quot;</span>, db=<span class="string">&quot;usersdb&quot;</span>)</span><br><span class="line">    cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 执行SQL语句（有SQL注入风险，稍后讲解）</span></span><br><span class="line">    <span class="comment"># sql = &#x27;insert into users(name,password)values(&quot;alex&quot;,&quot;sb&quot;)&#x27;</span></span><br><span class="line">    sql = <span class="string">&#x27;insert into users(name,password) values(&quot;&#123;&#125;&quot;,&quot;&#123;&#125;&quot;)&#x27;</span>.<span class="built_in">format</span>(user, password)</span><br><span class="line">    </span><br><span class="line">    cursor.execute(sql)</span><br><span class="line">    conn.commit()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 关闭数据库连接</span></span><br><span class="line">    cursor.close()</span><br><span class="line">    conn.close()</span><br><span class="line"></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;注册成功，用户名：&#123;&#125;,密码:&#123;&#125;&quot;</span>.<span class="built_in">format</span>(user, password))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span>():</span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&quot;用户登录&quot;</span>)</span><br><span class="line"></span><br><span class="line">    user = <span class="built_in">input</span>(<span class="string">&quot;请输入用户名：&quot;</span>)</span><br><span class="line">    password = <span class="built_in">input</span>(<span class="string">&quot;请输入密码：&quot;</span>)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 连接指定数据</span></span><br><span class="line">    conn = pymysql.connect(host=<span class="string">&#x27;127.0.0.1&#x27;</span>, port=<span class="number">3306</span>, user=<span class="string">&#x27;root&#x27;</span>, passwd=<span class="string">&#x27;root123&#x27;</span>, charset=<span class="string">&quot;utf8&quot;</span>, db=<span class="string">&quot;usersdb&quot;</span>)</span><br><span class="line">    cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line">    <span class="comment"># 执行SQL语句（有SQL注入风险，稍后讲解）</span></span><br><span class="line">    <span class="comment"># sql = select * from users where name=&#x27;wupeiqi&#x27; and password=&#x27;123&#x27;</span></span><br><span class="line">    sql = <span class="string">&quot;select * from users where name=&#x27;&#123;&#125;&#x27; and password=&#x27;&#123;&#125;&#x27;&quot;</span>.<span class="built_in">format</span>(user, password)</span><br><span class="line">    cursor.execute(sql)</span><br><span class="line">    </span><br><span class="line">    result = cursor.fetchone() <span class="comment"># 去向mysql获取结果</span></span><br><span class="line">    <span class="comment"># None</span></span><br><span class="line">    <span class="comment"># (1,wupeiqi,123)</span></span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="comment"># 关闭数据库连接</span></span><br><span class="line">    cursor.close()</span><br><span class="line">    conn.close()</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> result:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;登录成功&quot;</span>, result)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;登录失败&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">run</span>():</span></span><br><span class="line">    choice = <span class="built_in">input</span>(<span class="string">&quot;1.注册；2.登录&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> choice == <span class="string">&#x27;1&#x27;</span>:</span><br><span class="line">        register()</span><br><span class="line">    <span class="keyword">elif</span> choice == <span class="string">&#x27;2&#x27;</span>:</span><br><span class="line">        login()</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;输入错误&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    run()</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>So，你会发现， 在项目开发时，数据库 &amp; 数据表 的操作其实就做那么一次，最最常写的还是 对数据行 的操作。</p>
<h2 id="5-关于SQL注入"><a href="#5-关于SQL注入" class="headerlink" title="5.关于SQL注入"></a>5.关于SQL注入</h2><p>假如，你开发了一个用户认证的系统，应该用户登录成功后才能正确的返回相应的用户结果。 </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输入用户名和密码</span></span><br><span class="line">user = <span class="built_in">input</span>(<span class="string">&quot;请输入用户名：&quot;</span>) <span class="comment"># &#x27; or 1=1 -- </span></span><br><span class="line">pwd = <span class="built_in">input</span>(<span class="string">&quot;请输入密码：&quot;</span>) <span class="comment"># 123</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">conn = pymysql.connect(host=<span class="string">&#x27;127.0.0.1&#x27;</span>, port=<span class="number">3306</span>, user=<span class="string">&#x27;root&#x27;</span>, passwd=<span class="string">&#x27;root123&#x27;</span>, charset=<span class="string">&quot;utf8&quot;</span>,db=<span class="string">&#x27;usersdb&#x27;</span>)</span><br><span class="line">cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 基于字符串格式化来 拼接SQL语句</span></span><br><span class="line"><span class="comment"># sql = &quot;select * from users where name=&#x27;alex&#x27; and password=&#x27;123&#x27;&quot;</span></span><br><span class="line"><span class="comment"># sql = &quot;select * from users where name=&#x27;&#x27; or 1=1 -- &#x27; and password=&#x27;123&#x27;&quot;</span></span><br><span class="line">sql = <span class="string">&quot;select * from users where name=&#x27;&#123;&#125;&#x27; and password=&#x27;&#123;&#125;&#x27;&quot;</span>.<span class="built_in">format</span>(user, pwd)</span><br><span class="line">cursor.execute(sql)</span><br><span class="line"></span><br><span class="line">result = cursor.fetchone()</span><br><span class="line"><span class="built_in">print</span>(result) <span class="comment"># None，不是None</span></span><br><span class="line"></span><br><span class="line">cursor.close()</span><br><span class="line">conn.close()</span><br></pre></td></tr></table></figure>



<p>如果用户在输入user时，输入了：   <code>&#39; or 1=1 --  </code>    ，这样即使用户输入的密码不存在，也会可以通过验证。</p>
<p><strong>为什么呢？</strong></p>
<p>因为在SQL拼接时，拼接后的结果是：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">select * from users where name=&#x27;&#x27; or 1=1 -- &#x27; and password=&#x27;123&#x27;</span><br></pre></td></tr></table></figure>

<p>注意：在MySQL中 <code>--</code> 表示注释。</p>
<p><strong>那么，在Python开发中 如何来避免SQL注入呢？</strong></p>
<p>切记，SQL语句不要在使用python的字符串格式化，而是使用pymysql的execute方法。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pymysql</span><br><span class="line"></span><br><span class="line"><span class="comment"># 输入用户名和密码</span></span><br><span class="line">user = <span class="built_in">input</span>(<span class="string">&quot;请输入用户名：&quot;</span>)</span><br><span class="line">pwd = <span class="built_in">input</span>(<span class="string">&quot;请输入密码：&quot;</span>)</span><br><span class="line"></span><br><span class="line">conn = pymysql.connect(host=<span class="string">&#x27;127.0.0.1&#x27;</span>, port=<span class="number">3306</span>, user=<span class="string">&#x27;root&#x27;</span>, passwd=<span class="string">&#x27;root123&#x27;</span>, charset=<span class="string">&quot;utf8&quot;</span>, db=<span class="string">&#x27;userdb&#x27;</span>)</span><br><span class="line"></span><br><span class="line">cursor = conn.cursor()</span><br><span class="line"></span><br><span class="line">cursor.execute(<span class="string">&quot;select * from users where name=%s and password=%s&quot;</span>, [user, pwd])</span><br><span class="line"><span class="comment"># 或</span></span><br><span class="line"><span class="comment"># cursor.execute(&quot;select * from users where name=%(n1)s and password=%(n2)s&quot;, &#123;&quot;n1&quot;: user, &#x27;n2&#x27;: pwd&#125;)</span></span><br><span class="line"></span><br><span class="line">result = cursor.fetchone()</span><br><span class="line"><span class="built_in">print</span>(result)</span><br><span class="line"></span><br><span class="line">cursor.close()</span><br><span class="line">conn.close()</span><br></pre></td></tr></table></figure>





<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p><img src="https://gitee.com/a_bowl_of_tea/img/raw/master/MySQL_img/image-20210508102020237.png" alt="image-20210508102020237"></p>
<p>除了 【第5步 用户授权】以外，现在使用的是默认root账户（拥有最大权限），上述所有的过程已讲解完毕。</p>
<p>本节内容大家需要掌握：</p>
<ul>
<li>安装和启动MySQL</li>
<li>SQL语句：<ul>
<li>数据库操作</li>
<li>表操作</li>
<li>数据行操作</li>
</ul>
</li>
<li>基于Python操作MySQL</li>
<li>注意SQL注入的问题</li>
</ul>
<h2 id="作业"><a href="#作业" class="headerlink" title="作业"></a>作业</h2><ol>
<li><p>根据要求 创建表 结构并编写相应的SQL语句（基于MySQL自带客户端操作）</p>
<table>
<thead>
<tr>
<th>列名</th>
<th>类型</th>
<th>备注</th>
</tr>
</thead>
<tbody><tr>
<td>id</td>
<td>int</td>
<td>不为空 &amp; 自增 &amp; 主键</td>
</tr>
<tr>
<td>name</td>
<td>varchar(32)</td>
<td>不为空</td>
</tr>
<tr>
<td>password</td>
<td>varchar(64)</td>
<td>不为空</td>
</tr>
<tr>
<td>gender</td>
<td>char(1)</td>
<td>不为空，支持：男、女</td>
</tr>
<tr>
<td>email</td>
<td>varchar(64)</td>
<td>可以为空</td>
</tr>
<tr>
<td>amount</td>
<td>decimal(10,2)</td>
<td>不为空 &amp; 默认值为 0</td>
</tr>
<tr>
<td>ctime</td>
<td>datetime</td>
<td>新增时的时间<br />提示：可基于datetime模块实现</td>
</tr>
</tbody></table>
<ul>
<li><p>根据上述表的要求创建相应的数据和表结构（注意编码）。</p>
</li>
<li><p>任意插入5条数据。</p>
</li>
<li><p>将 <code>id&gt;3</code>的所有人的性别改为  男。</p>
</li>
<li><p>查询余额 <code>amount&gt;1000</code>的所有用户。</p>
</li>
<li><p>让每个人的余额在自己原的基础上 +1000 。</p>
</li>
<li><p>删除性别为男的所有数据。</p>
</li>
<li><p>通过Python代码实现上述除了第一个以外的操作。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">插入5条数据时，ctime那一列不要自己写“2021-11-11.。。” 而是使用datatime模块生成当前时间。</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>编写脚本实现将 csv 文件的内容录入到 MySQL 数据库中。<br>要求：自己创建一个自增列作为主键（不要用csv文件中的第一列作为主键）。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line">1715046,河北大学取消考试学生紧急离校,老师:回不了家的到老师家过年,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715046-15562045_adpkg-ad_hd.mp4</span><br><span class="line">1715020,重庆两口子因琐事吵架，男子怒将自家车推进涪江,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715020-15561817_adpkg-ad_hd.mp4</span><br><span class="line">1715031,成都九峰山因雪景引游客暴增，致垃圾遍地野猴觅食,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715031-15561980_adpkg-ad_hd.mp4</span><br><span class="line">1715014,女子子宫摘除32年后CT报告称未见异常，医生：贴的模版忘删了,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715014-15561686_adpkg-ad_hd.mp4</span><br><span class="line">1715025,监控画面曝光！甘肃天水一公交车与救护车相撞后坠桥,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715025-15561875_adpkg-ad_hd.mp4</span><br><span class="line">1715010,男子称退伍后发现被贷款100万：征信逾期数十次，非自己签名,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715010-15561845_adpkg-ad_hd.mp4</span><br><span class="line">1715007,东北老交警零下43度执勤落下老寒腿:穿2斤重棉裤,已习以为常,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715007-15561958_adpkg-ad_hd.mp4</span><br><span class="line">1715011,女教师公寓熟睡被同事弟弟连砍数刀：全身刀疤，不敢告诉父母,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715011-15561664_adpkg-ad_hd.mp4</span><br><span class="line">1714970,网曝江西一村庄现两千平违建，房主回应：建给村里当文化中心,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714970-15561752_adpkg-ad_hd.mp4</span><br><span class="line">1715006,河南一新建足球场内惊现坟墓，官方：会尽快迁坟,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715006-15561679_adpkg-ad_hd.mp4</span><br><span class="line">1715009,老师收到毕业24年学生送的定制台历：他高考失利，我开导过,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715009-15561658_adpkg-ad_hd.mp4</span><br><span class="line">1715000,尚德机构回应未兑现宝马奖励：名单仍在确认中，会负责到底,https://video.pearvideo.com/mp4/adshort/20210105/cont-1715000-15561545_adpkg-ad_hd.mp4</span><br><span class="line">1714993,沈阳重点管控区日常产90吨生活垃圾，重点疫点垃圾由专人运走,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714993-15561434_adpkg-ad_hd.mp4</span><br><span class="line">1714995,消费者称遭移动外呼10088套路换套餐，客服致歉：口径有问题,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714995-1427-174135_adpkg-ad_hd.mp4</span><br><span class="line">1714979,泪流满面！武警相隔两千公里与妻子隔屏举行婚礼,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714979-15561542_adpkg-ad_hd.mp4</span><br><span class="line">1714992,村民结婚两男子拄拐上门要钱：给少了不走，反问&quot;咋拿得出手&quot;,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714992-15561429_adpkg-ad_hd.mp4</span><br><span class="line">1714457,36年嫌疑人：儿女被骂“杀人犯的孩子”，不想把骂名带进棺材,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714457-1491-170515_adpkg-ad_hd.mp4</span><br><span class="line">1714981,男子偷手机被发现挣脱失主逃跑，执勤辅警狂追八百米擒获,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714981-99-172939_adpkg-ad_hd.mp4</span><br><span class="line">1714977,八旬老太捡拾垃圾成瘾，堆满楼道院子漫进邻居家,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714977-15561306_adpkg-ad_hd.mp4</span><br><span class="line">1714972,昆明一楼盘消防喷淋离地仅2米1，业主吐槽：直接当喷头用,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714972-15561247_adpkg-ad_hd.mp4</span><br><span class="line">1714973,居民家浓烟弥漫邻居敲门不应，民警赶来一看是屋主在熏腊肉,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714973-15561249_adpkg-ad_hd.mp4</span><br><span class="line">1714966,石家庄有超市停业，学校紧急放假，学生：下午考试被临时取消,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714966-15561248_adpkg-ad_hd.mp4</span><br><span class="line">1714902,杭州地铁7号线施工大揭秘：940天完成近40公里地铁线,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714902-15561394_adpkg-ad_hd.mp4</span><br><span class="line">1714928,沈阳已设置重点管控区域，大连志愿者挨家挨户配送生活物资,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714928-15561018_adpkg-ad_hd.mp4</span><br><span class="line">1714950,女孩考第一溺亡双胞胎姐姐不吃不喝，家属诉求：给予心理疏导,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714950-15561100_adpkg-ad_hd.mp4</span><br><span class="line">1714924,70万1针特效药降价，2岁患儿母亲哽咽：会拼全力救孩子,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714924-58-162201_adpkg-ad_hd.mp4</span><br><span class="line">1714930,贵州大叔嫁女陪嫁28万现金和一套房：儿子结婚只花了十几万,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714930-15561017_adpkg-ad_hd.mp4</span><br><span class="line">1714927,张家口云顶滑雪场通报一滑雪者摔倒身亡：警方已介入,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714927-15560963_adpkg-ad_hd.mp4</span><br><span class="line">1714926,邢台全面进入战时状态，小区进出需要健康码,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714926-15560829_adpkg-ad_hd.mp4</span><br><span class="line">1714918,石家庄多个小区采取封闭管理：发现阳性检测者，全员核酸检测,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714918-15560835_adpkg-ad_hd.mp4</span><br><span class="line">1714693,兰大女生当兵2年后重返校园：学会自律，珍惜在校时光,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714693-15560791_adpkg-ad_hd.mp4</span><br><span class="line">1714920,猴哥尝到投喂甜头赖老太家不走，逗鸡毁菜气到村民报警,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714920-15560793_adpkg-ad_hd.mp4</span><br><span class="line">1714916,沈阳确诊出车司机搭载的抚顺3名乘客全部找到，核酸均为阴性,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714916-15560758_adpkg-ad_hd.mp4</span><br><span class="line">1714894,轿车被48米建筑垃圾围堵三个月，车主无法用车叫苦不迭,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714894-15560731_adpkg-ad_hd.mp4</span><br><span class="line">1714861,考第一被质疑后溺亡女孩同学：她自尊心强，曾说被怀疑作弊,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714861-15560701_adpkg-ad_hd.mp4</span><br><span class="line">1714886,东北汉子冲进火场救人被熏成黑脸：差几秒，我就倒在里面了,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714886-15560659_adpkg-ad_hd.mp4</span><br><span class="line">1714908,探访石家庄疫情高风险地区：部分村庄封村，外村人一律不让进,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714908-15560638_adpkg-ad_hd.mp4</span><br><span class="line">1714906,“北京时间”产生于西安，科学家解读选址考量因素,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714906-15560549_adpkg-ad_hd.mp4</span><br><span class="line">1714907,16人聚餐吃了800元无人结账，老板询问反遭怼：多大点事儿,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714907-15560637_adpkg-ad_hd.mp4</span><br><span class="line">1714892,重庆一地铁站出口建在坡顶，居民：期待未来的变化,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714892-15560550_adpkg-ad_hd.mp4</span><br><span class="line">1714900,河北南宫一小区发现高度疑似密接人员，小区全面封闭只进不出,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714900-15560548_adpkg-ad_hd.mp4</span><br><span class="line">1714901,杭州运河边8平米小书摊开了13年，店主兼职拉货补贴,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714901-15560544_adpkg-ad_hd.mp4</span><br><span class="line">1714877,河南商丘鹦鹉卖家被追刑责，养殖户：不敢卖不敢放，放也犯法,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714877-15560499_adpkg-ad_hd.mp4</span><br><span class="line">1714895,石家庄小果庄村1天增加8例确诊病例，为全国唯一高风险地区,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714895-15560459_adpkg-ad_hd.mp4</span><br><span class="line">1714801,48岁女教师重新高考学法律：直接进入老年生活是种损失,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714801-15560352_adpkg-ad_hd.mp4</span><br><span class="line">1714873,不认失散聋哑儿夫妻已接走儿子，养父：两验DNA，归属没说清,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714873-15560356_adpkg-ad_hd.mp4</span><br><span class="line">1714846,7岁男童煤气中毒脑死亡，父母含泪为其捐器官救同龄人,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714846-15560326_adpkg-ad_hd.mp4</span><br><span class="line">1714875,连夜出发！衡水110名护士紧急集结支援中风险地区,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714875-15560268_adpkg-ad_hd.mp4</span><br><span class="line">1713843,打满全场丨院感专家李素英回忆援鄂：90后00后医护最让我感动,https://video.pearvideo.com/mp4/adshort/20210104/cont-1713843-15559433_adpkg-ad_hd.mp4</span><br><span class="line">1714869,河北新增14例确诊30例无症状，石家庄一村庄调整为高风险地区,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714869-15560218_adpkg-ad_hd.mp4</span><br><span class="line">1714862,应急部披露襄汾饭店坍塌致29死细节：8次违规扩建，监管不严,https://video.pearvideo.com/mp4/adshort/20210105/cont-1714862-15560157_adpkg-ad_hd.mp4</span><br></pre></td></tr></table></figure></li>
</ol>

      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-封装logger、封装项目异常处理、二次封装Response模块" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/23/%E5%B0%81%E8%A3%85logger%E3%80%81%E5%B0%81%E8%A3%85%E9%A1%B9%E7%9B%AE%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E3%80%81%E4%BA%8C%E6%AC%A1%E5%B0%81%E8%A3%85Response%E6%A8%A1%E5%9D%97/" class="article-date">
      <time datetime="2021-11-22T16:00:00.000Z" itemprop="datePublished">2021-11-23</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/23/%E5%B0%81%E8%A3%85logger%E3%80%81%E5%B0%81%E8%A3%85%E9%A1%B9%E7%9B%AE%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E3%80%81%E4%BA%8C%E6%AC%A1%E5%B0%81%E8%A3%85Response%E6%A8%A1%E5%9D%97/">封装logger、封装项目异常处理、二次封装Response模块</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <h1 id="1-封装logger"><a href="#1-封装logger" class="headerlink" title="1 封装logger"></a>1 封装logger</h1><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> dev.py</span></span><br><span class="line"><span class="meta"></span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 真实项目上线后，日志文件打印级别不能过低，因为一次日志记录就是一次文件io操作</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> django中使用日志</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> 再django配置文件中复制日志字典</span></span><br><span class="line"><span class="meta">#</span><span class="bash"><span class="comment"># 1 日志相关配置（跟原生日志一样）</span></span></span><br><span class="line">LOGGING = &#123;</span><br><span class="line">    &#x27;version&#x27;: 1,</span><br><span class="line">    &#x27;disable_existing_loggers&#x27;: False,</span><br><span class="line">    &#x27;formatters&#x27;: &#123;</span><br><span class="line">        &#x27;verbose&#x27;: &#123;</span><br><span class="line">            &#x27;format&#x27;: &#x27;%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s&#x27;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#x27;simple&#x27;: &#123;</span><br><span class="line">            &#x27;format&#x27;: &#x27;%(levelname)s %(module)s %(lineno)d %(message)s&#x27;</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#x27;filters&#x27;: &#123;</span><br><span class="line">        &#x27;require_debug_true&#x27;: &#123;</span><br><span class="line">            &#x27;()&#x27;: &#x27;django.utils.log.RequireDebugTrue&#x27;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#x27;handlers&#x27;: &#123;</span><br><span class="line">        &#x27;console&#x27;: &#123;</span><br><span class="line">            # 实际开发建议使用WARNING</span><br><span class="line">            &#x27;level&#x27;: &#x27;DEBUG&#x27;,</span><br><span class="line">            &#x27;filters&#x27;: [&#x27;require_debug_true&#x27;],</span><br><span class="line">            &#x27;class&#x27;: &#x27;logging.StreamHandler&#x27;,</span><br><span class="line">            &#x27;formatter&#x27;: &#x27;simple&#x27;</span><br><span class="line">        &#125;,</span><br><span class="line">        &#x27;file&#x27;: &#123;</span><br><span class="line">            # 实际开发建议使用ERROR</span><br><span class="line">            &#x27;level&#x27;: &#x27;INFO&#x27;,</span><br><span class="line">            &#x27;class&#x27;: &#x27;logging.handlers.RotatingFileHandler&#x27;,</span><br><span class="line">            # 日志位置,日志文件名,日志保存目录必须手动创建，注：这里的文件路径要注意BASE_DIR代表的是小luffyapi</span><br><span class="line">            &#x27;filename&#x27;: os.path.join(os.path.dirname(BASE_DIR), &quot;logs&quot;, &quot;luffy.log&quot;),</span><br><span class="line">            # 日志文件的最大值,这里我们设置300M</span><br><span class="line">            &#x27;maxBytes&#x27;: 300 * 1024 * 1024,</span><br><span class="line">            # 日志文件的数量,设置最大日志数量为10</span><br><span class="line">            &#x27;backupCount&#x27;: 10,</span><br><span class="line">            # 日志格式:详细格式</span><br><span class="line">            &#x27;formatter&#x27;: &#x27;verbose&#x27;,</span><br><span class="line">            # 文件内容编码</span><br><span class="line">            &#x27;encoding&#x27;: &#x27;utf-8&#x27;</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    # 日志对象</span><br><span class="line">    &#x27;loggers&#x27;: &#123;</span><br><span class="line">        &#x27;django&#x27;: &#123;</span><br><span class="line">            &#x27;handlers&#x27;: [&#x27;console&#x27;, &#x27;file&#x27;],</span><br><span class="line">            &#x27;propagate&#x27;: True, # 是否让日志信息继续冒泡给其他的日志处理系统</span><br><span class="line">        &#125;,</span><br><span class="line">        &#x27;lqz&#x27;: &#123;</span><br><span class="line">            &#x27;handlers&#x27;: [&#x27;console&#x27;],</span><br><span class="line">            &#x27;propagate&#x27;: True,  # 是否让日志信息继续冒泡给其他的日志处理系统</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="utils-logging-py"><a href="#utils-logging-py" class="headerlink" title="utils/logging.py"></a>utils/logging.py</h2><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mport logging</span><br><span class="line">def get_logger(l=&#x27;django&#x27;):</span><br><span class="line">    return logging.getLogger(l)</span><br></pre></td></tr></table></figure>

<p>使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> utils <span class="keyword">import</span> logging</span><br><span class="line">logger = logging.get_logger()</span><br><span class="line">logger.info(<span class="string">&#x27;我是日志&#x27;</span>)</span><br></pre></td></tr></table></figure>



<h1 id="2-封装项目异常处理"><a href="#2-封装项目异常处理" class="headerlink" title="2 封装项目异常处理"></a>2 封装项目异常处理</h1><h3 id="utils-exception-py"><a href="#utils-exception-py" class="headerlink" title="utils/exception.py"></a>utils/exception.py</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## 新建utils/excepitons.py</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> exception_handler <span class="keyword">as</span> drf_exception_handler</span><br><span class="line"><span class="comment"># 导入Response</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> Response</span><br><span class="line"><span class="comment"># 导入status</span></span><br><span class="line"><span class="keyword">from</span> rest_framework <span class="keyword">import</span> status</span><br><span class="line"></span><br><span class="line"><span class="comment"># 导入utils文件夹下的logging</span></span><br><span class="line"><span class="keyword">from</span> utils <span class="keyword">import</span> logging</span><br><span class="line">logger = logging.get_logger()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 捕捉全局异常的函数，重写了该函数</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">exception_handler</span>(<span class="params">exc, context</span>):</span></span><br><span class="line">    response = drf_exception_handler(exc, context)</span><br><span class="line">    <span class="keyword">if</span> response <span class="keyword">is</span> <span class="literal">None</span>:  <span class="comment"># drf没有处理的，django的异常</span></span><br><span class="line">        <span class="comment"># response = Response(&#123;&#x27;detail&#x27;: &#x27;服务器异常，请重试...&#x27;&#125;, status=status.HTTP_500_INTERNAL_SERVER_ERROR)</span></span><br><span class="line">        response = Response(&#123;<span class="string">&#x27;code&#x27;</span>: <span class="number">999</span>, <span class="string">&#x27;msg&#x27;</span>: <span class="string">&#x27;服务器异常，请重试...&#x27;</span>&#125;)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        response = Response(&#123;<span class="string">&#x27;code&#x27;</span>: <span class="number">998</span>, <span class="string">&#x27;msg&#x27;</span>: response.data[<span class="string">&#x27;detail&#x27;</span>]&#125;)</span><br><span class="line">    <span class="comment"># 记录服务器异常,drf和django的异常，都记录</span></span><br><span class="line">    logger.critical(<span class="string">&#x27;%s&#x27;</span> % exc)</span><br><span class="line">    <span class="keyword">return</span> response</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="settings-py"><a href="#settings-py" class="headerlink" title="settings.py"></a>settings.py</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">REST_FRAMEWORK = &#123;</span><br><span class="line">    &#x27;EXCEPTION_HANDLER&#x27;: &#x27;utils.exception.exception_handler&#x27;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="3-二次封装Response模块"><a href="#3-二次封装Response模块" class="headerlink" title="3 二次封装Response模块"></a>3 二次封装Response模块</h1><h3 id="utils-response-py"><a href="#utils-response-py" class="headerlink" title="utils/response.py"></a>utils/response.py</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">from rest_framework.response import Response</span><br><span class="line"></span><br><span class="line">class APIResponse(Response):</span><br><span class="line">    def __init__(self, status=0, msg=&#x27;ok&#x27;, http_status=None, headers=None, exception=False, **kwargs):</span><br><span class="line">        data = &#123;</span><br><span class="line">            &#x27;status&#x27;: status,</span><br><span class="line">            &#x27;msg&#x27;: msg,</span><br><span class="line">        &#125;</span><br><span class="line">        if kwargs:</span><br><span class="line">            data.update(kwargs)</span><br><span class="line">        super().__init__(data=data, status=http_status, headers=headers, exception=exception)</span><br></pre></td></tr></table></figure>


      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
    <article id="post-Python" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a  href="/chen-changxiao/2021/11/19/Python/" class="article-date">
      <time datetime="2021-11-19T14:55:00.000Z" itemprop="datePublished">2021-11-19</time>
</a>

    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 itemprop="name">
      <a  class="article-title" href="/chen-changxiao/2021/11/19/Python/">Python</a>
    </h1>
  


      </header>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <p>Python博客</p>
<p>上传博客文章命令</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hexo cl &amp;&amp; hexo g &amp;&amp; hexo g</span><br></pre></td></tr></table></figure>

<p>直接推送文章</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hexo d</span><br></pre></td></tr></table></figure>


      
    </div>
    
    <div class="article-info article-info-index">
      
      

      
      
      <div class="clearfix"></div>
    </div>
    
  </div>
  
</article>











  
  

</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                &copy; 2021 昌晓
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank">Hexo &nbsp;&nbsp;</a><a href="https://github.com/maochunguang" target="_blank">Blog</a> by tommy
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" >极客到访数: 
                            <span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>, </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit">本页阅读量: 
                            <span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>

    </div>
    
<script src="https://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>


<script src="/chen-changxiao/js/main.js"></script>


    <script>
        $(document).ready(function() {
            var backgroundnum = 1;
            var backgroundimg = "url(/background/bg-x.jpg)".replace(/x/gi, Math.ceil(Math.random() * backgroundnum));
            $("#mobile-nav").css({"background-image": backgroundimg,"background-size": "cover","background-position": "center"});
            $(".left-col").css({"background-image": backgroundimg,"background-size": "cover","background-position": "center"});
        })
    </script>


<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'xxxxx', 'auto');
ga('send', 'pageview');

</script>
<!-- End Google Analytics -->



	<script>
	var _hmt = _hmt || [];
	(function() {
	  var hm = document.createElement("script");
	  hm.src = "//hm.baidu.com/hm.js?xxxxxx";
	  var s = document.getElementsByTagName("script")[0]; 
	  s.parentNode.insertBefore(hm, s);
	})();
	</script>



<div class="scroll" id="scroll">
    <a href="#"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments"><i class="fa fa-comments-o"></i></a>
    <a href="#footer"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    $(document).ready(function() {
        if ($("#comments").length < 1) {
            $("#scroll > a:nth-child(2)").hide();
        };
    })
</script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

  <script language="javascript">
    $(function() {
        $("a[title]").each(function() {
            var a = $(this);
            var title = a.attr('title');
            if (title == undefined || title == "") return;
            a.data('title', title).removeAttr('title').hover(
            function() {
                var offset = a.offset();
                $("<div id=\"anchortitlecontainer\"></div>").appendTo($("body")).html(title).css({
                    top: offset.top - a.outerHeight() - 15,
                    left: offset.left + a.outerWidth()/2 + 1
                }).fadeIn(function() {
                    var pop = $(this);
                    setTimeout(function() {
                        pop.remove();
                    }, pop.text().length * 800);
                });
            }, function() {
                $("#anchortitlecontainer").remove();
            });
        });
    });
</script>


  </div>
</body>
</html>